writing an array to json file

Solutions on MaxInterview for writing an array to json file by the best coders in the world

showing results for - "writing an array to json file"
Diego Alejandro
30 Apr 2017
1package com.howtodoinjava.demo.jsonsimple;
2 
3import java.io.FileWriter;
4import java.io.IOException;
5import org.json.simple.JSONArray;
6import org.json.simple.JSONObject;
7 
8public class WriteJSONExample
9{
10    @SuppressWarnings("unchecked")
11    public static void main( String[] args )
12    {
13        //First Employee
14        JSONObject employeeDetails = new JSONObject();
15        employeeDetails.put("firstName", "Lokesh");
16        employeeDetails.put("lastName", "Gupta");
17        employeeDetails.put("website", "howtodoinjava.com");
18         
19        JSONObject employeeObject = new JSONObject(); 
20        employeeObject.put("employee", employeeDetails);
21         
22        //Second Employee
23        JSONObject employeeDetails2 = new JSONObject();
24        employeeDetails2.put("firstName", "Brian");
25        employeeDetails2.put("lastName", "Schultz");
26        employeeDetails2.put("website", "example.com");
27         
28        JSONObject employeeObject2 = new JSONObject(); 
29        employeeObject2.put("employee", employeeDetails2);
30         
31        //Add employees to list
32        JSONArray employeeList = new JSONArray();
33        employeeList.add(employeeObject);
34        employeeList.add(employeeObject2);
35         
36        //Write JSON file
37        try (FileWriter file = new FileWriter("employees.json")) {
38            //We can write any JSONArray or JSONObject instance to the file
39            file.write(employeeList.toJSONString()); 
40            file.flush();
41 
42        } catch (IOException e) {
43            e.printStackTrace();
44        }
45    }
46}
47
similar questions
jsonarray to list in java