1package com.howtodoinjava.demo.jsonsimple;
2
3import java.io.FileNotFoundException;
4import java.io.FileReader;
5import java.io.IOException;
6
7import org.json.simple.JSONArray;
8import org.json.simple.JSONObject;
9import org.json.simple.parser.JSONParser;
10import org.json.simple.parser.ParseException;
11
12public class ReadJSONExample
13{
14 @SuppressWarnings("unchecked")
15 public static void main(String[] args)
16 {
17 //JSON parser object to parse read file
18 JSONParser jsonParser = new JSONParser();
19
20 try (FileReader reader = new FileReader("employees.json"))
21 {
22 //Read JSON file
23 Object obj = jsonParser.parse(reader);
24
25 JSONArray employeeList = (JSONArray) obj;
26 System.out.println(employeeList);
27
28 //Iterate over employee array
29 employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );
30
31 } catch (FileNotFoundException e) {
32 e.printStackTrace();
33 } catch (IOException e) {
34 e.printStackTrace();
35 } catch (ParseException e) {
36 e.printStackTrace();
37 }
38 }
39
40 private static void parseEmployeeObject(JSONObject employee)
41 {
42 //Get employee object within list
43 JSONObject employeeObject = (JSONObject) employee.get("employee");
44
45 //Get employee first name
46 String firstName = (String) employeeObject.get("firstName");
47 System.out.println(firstName);
48
49 //Get employee last name
50 String lastName = (String) employeeObject.get("lastName");
51 System.out.println(lastName);
52
53 //Get employee website name
54 String website = (String) employeeObject.get("website");
55 System.out.println(website);
56 }
57}
58
1package com.howtodoinjava.demo.jsonsimple;
2
3import java.io.FileWriter;
4import java.io.IOException;
5
6import org.json.simple.JSONArray;
7import org.json.simple.JSONObject;
8
9public class WriteJSONExample
10{
11 @SuppressWarnings("unchecked")
12 public static void main( String[] args )
13 {
14 //First Employee
15 JSONObject employeeDetails = new JSONObject();
16 employeeDetails.put("firstName", "Lokesh");
17 employeeDetails.put("lastName", "Gupta");
18 employeeDetails.put("website", "howtodoinjava.com");
19
20 JSONObject employeeObject = new JSONObject();
21 employeeObject.put("employee", employeeDetails);
22
23 //Second Employee
24 JSONObject employeeDetails2 = new JSONObject();
25 employeeDetails2.put("firstName", "Brian");
26 employeeDetails2.put("lastName", "Schultz");
27 employeeDetails2.put("website", "example.com");
28
29 JSONObject employeeObject2 = new JSONObject();
30 employeeObject2.put("employee", employeeDetails2);
31
32 //Add employees to list
33 JSONArray employeeList = new JSONArray();
34 employeeList.add(employeeObject);
35 employeeList.add(employeeObject2);
36
37 //Write JSON file
38 try (FileWriter file = new FileWriter("employees.json")) {
39
40 file.write(employeeList.toJSONString());
41 file.flush();
42
43 } catch (IOException e) {
44 e.printStackTrace();
45 }
46 }
47}
48