我想解析JSON数组内的嵌套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());
}
我可以访问对象,但不能单独访问子对象。有没有办法遍历“flights”数组中的对象,并知道如果我再次遇到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等,以便知道哪个对象它属于。
我想这是Java。请标记你的问题。 – trincot