我想解析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