I'm trying to parse the nested JSON object within the JSON array. I'm not sure how to go about accessing all the objects and the Keys and Values within the nested JSON objects in a generic way.
{
"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
},
}
]
}
Here's what i've done so far.
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());
}
I'm able to access the objects but not the sub-objects separately. Is there a way to iterate through the object in the "flights" array and know somehow if i've encountered a JSON Object (e.g. "origin") again and loop inside it? Rather than doing the following
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");
Also, i want to access the keys as origin_code, origin_city and destination_code, destination_city etc. so as to know which object it belonged to.
-
I suppose this is Java. Please tag your question as such.trincot– trincot2017年09月16日 09:52:58 +00:00Commented Sep 16, 2017 at 9:52
1 Answer 1
You can do this
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(new FileReader("PathToFile.json"));
JSONArray jsonArray = (JSONArray) object.get("flights");
for(int i=0;i<jsonArray.size();i++){
JSONObject flightJSON = jsonArray.getJSONObject(i);
JSONObject origin = flightJSON.getJSONObject("origin");
String code = origin.get("code");
String city = origin.get("city");
String alternate_ident = origin.get("alternate_ident");
String airport_name = origin.get("airport_name");
//Similaryly for these
JSONObject destination = flightJSON.getJSONObject("destination");
JSONObject filed_departure_time = flightJSON.getJSONObject("filed_departure_time");
}
You need to know the structure to parse it but if you don't know whether it is array,object or other entities, you can try
Object object = json.get("key");
if (object instanceof JSONArray) {
// JSONObject
jsonArray = (JSONArray)object;
}else if (object instanceof JSONObject) {
// JSONArray
jsonObject = (JSONObject)object;
}else {
// String or Integer etc.
}