JSON数组中的嵌套JSON对象

时间:2017-09-16 08:26:00

标签: json

我正在尝试解析JSON数组中的嵌套JSON对象。我不确定如何以通用方式访问嵌套JSON对象中的所有对象以及键和值。

     {
        "flights": [
        {
            "ident": "AWI4207",
            "faFlightID": "AWI4207-1505297520-schedule-0000",
            "origin": {
                "code": "KORF",
                "city": "Norfolk, VA",
                "alternate_ident": "",
                "airport_name": "Norfolk Intl"
            },
            "destination": {
                "code": "KPHL",
                "city": "Philadelphia, PA",
                "alternate_ident": "",
                "airport_name": "Philadelphia Intl"
            },
            "filed_ete": 2400,
            "filed_departure_time": {
                "epoch": 1505470320,
                "tz": "EDT",
                "dow": "Friday",
                "time": "06:12AM",
                "date": "15/09/2017",
                "localtime": 1505455920
            },
        }
      ]
    }

这是我到目前为止所做的事情。

JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(new FileReader("PathToFile.json"));

JSONArray jsonArray = (JSONArray) object.get("flights");
Iterator<Object> eventJSONIterator = jsonArray.iterator();

while (eventJSONIterator.hasNext()) {
  JSONObject jsonEvent = (JSONObject) eventJSONIterator.next();
  System.out.println(jsonEvent.toString());
}

我能够分别访问对象而不是子对象。有没有办法迭代“flight”数组中的对象并知道我是否再次遇到JSON对象(例如“origin”)并在其中循环?而不是做以下

JSONObject mainObject = (JSONObject) jsonArray.get(0);

JSONObject origin = (JSONObject) mainObject.get("origin");
JSONObject destination = (JSONObject) mainObject.get("destination");
JSONObject filed_departure_time = (JSONObject) mainObject.get("filed_departure_time");

此外,我想访问密钥为origin_code,origin_city和destination_code,destination_city等,以便知道它属于哪个对象。

1 个答案:

答案 0 :(得分:1)

你可以这样做

src

您需要知道解析它的结构,但如果您不知道它是数组,对象还是其他实体,您可以尝试

img
相关问题