0

I have this in my json file(see below) and I want to read it to console.

{
"employeeData": {
  "employmentStartDate": "1997-12-3",
  "employmentEndDate": "1997-12-03",
  "suspensionPeriodList": [
    {"startDate":  "1997-05-01", "endDate":  "1997-07-31" },
    {"startDate":  "1997-08-02", "endDate":  "1997-09-31" }
  ]
}
}

I tried in some ways but my problem is the 'employeeData'. If it wasn't there I could easily get the employmentStartDate by JSONArray JSON = (JSONArray) JSONObj.get("employmentStartDate");

 JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader("src\\main\\resources\\input.json"));
            JSONObject JSONObj = (JSONObject) obj;

            JSONArray JSON = (JSONArray) JSONObj.get("employeeData");
            Iterator<String> iterator = JSON.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I tried to put the EmployeeData into an array but this doesn't work of course.

Robert Carlos
  • 31
  • 1
  • 7
  • Possible duplicate of [How to read json file into java with simple JSON library](https://stackoverflow.com/questions/10926353/how-to-read-json-file-into-java-with-simple-json-library) – Sudhir Ojha Apr 17 '19 at 07:38
  • `EmployeeData` is an object, not an array. Why are you reading it into an array? – RealSkeptic Apr 17 '19 at 08:18

1 Answers1

0

If you just want to print the JSON values to the console, you can try below code:

JSONParser parser = new JSONParser();
    try {
        JSONObject JSONObj = (JSONObject) parser.parse(new FileReader("src\\main\\resources\\input.json"));

        JSONObject employeeDataJSON = (JSONObject) JSONObj.get("employeeData");

        System.out.println("employmentStartDate :" + (String) employeeDataJSON.get("employmentStartDate"));
        System.out.println("employmentEndDate :" + (String) employeeDataJSON.get("employmentEndDate"));

        JSONArray suspensionPeriodList=(JSONArray) employeeDataJSON.get("suspensionPeriodList");
        suspensionPeriodList.forEach(e->{
            System.out.println(e);
        });


    } catch (Exception e) {
        e.printStackTrace();
    }

This will give output as:

employmentStartDate :1997-12-3
employmentEndDate :1997-12-03
{"endDate":"1997-07-31","startDate":"1997-05-01"}
{"endDate":"1997-09-31","startDate":"1997-08-02"}

You can print suspensionPeriodList values individually also.

PraBhu
  • 196
  • 3
  • 13