如何从文件中读取json格式

时间:2019-04-17 07:36:09

标签: java json

我在json文件中有此文件(请参见下文),我想将其读取为控制台文件。

{
"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" }
  ]
}
}

我尝试了一些方法,但是我的问题是'employeeData'。如果不在那里 我可以通过JSONArray JSON = (JSONArray) JSONObj.get("employmentStartDate");

轻松获得jobStartDate
 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();
        }
    }

我试图将EmployeeData放入一个数组,但这当然行不通。

1 个答案:

答案 0 :(得分:0)

如果您只想将JSON值打印到控制台,则可以尝试以下代码:

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();
    }

这将输出为:

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

您还可以单独打印suspendPeriodList值。