2017-09-16 65 views
0

我想解析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等,以便知道哪個對象它屬於。

+0

我想這是Java。請標記你的問題。 – trincot

回答

1

你可以做到這一點

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"); 


    } 

你需要知道的結構解析,但如果你不知道它是否是數組,對象或其他實體,你可以嘗試

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. 
} 
+0

for循環中的jsonArray.length()顯示出於某種原因的錯誤。 「方法length()對於JSONArray類型是未定義的」 – Alohamora153

+0

是否爲JSONArray導入了org.json.JSONArray? –

+1

查看更新的答案jsonArray.size()您的情況 –