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