2014-04-01 161 views
1

這是我的JSON輸出。我想返回 「ID」:從指令 「9040」,但我有麻煩如何解析JSON對象以獲取數組中的數組?

{ 
    "packages": [ 
    { 
     "instructions": [ 
     { 
     "id": "9040", 
     "fn": "test.xml", 
     "@type": "down", 
     "fp": "" 
    } 
    ], 
    "id": "47968", 
    "time": 1396036698630, 
    "priority": 0 
} 

] }

這裏是我的代碼,返回 「包」 - > 「ID」

  JSONObject jObject = new JSONObject(json); 
     JSONArray jsonMainNode = jObject.optJSONArray("packages"); 
     int lengthJsonArr = jsonMainNode.length(); 
     for(int i=0; i < lengthJsonArr; i++) 
     { 
      /****** Get Object for each JSON node.***********/ 
      JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 
      fileid = Integer.parseInt(jsonChildNode.optString("id").toString()); 
      if (fileid > 0) 

      Log.i("JSON parse", "id = "+ fileid); 
     } 

任何幫助將不勝感激。

謝謝

回答

1

您忘記JSONArray說明

{ 
    "packages": [ 
     { 
      "instructions": [ 
       { 
        "id": "9040", 
        "fn": "test.xml", 
        "@type": "down", 
        "fp": "" 
       } 
      ], 
      "id": "47968", 
      "time": 1396036698630, 
      "priority": 0 
     } 
    ] 
} 

爲了解析

JSONObject jObject = new JSONObject(json); 
JSONArray jsonMainNode = jObject.optJSONArray("packages"); 
JSONObject jb = (JSONObject) jsonMainNode.get(0); 
JSONArray instructions = jb.getJSONArray("instructions"); 
JSONObject jb1 = (JSONObject) instructions.get(0); 
String id = jb1.getString("id"); 
+0

美麗。這就像一個魅力..非常感謝你 – motti10

+0

@ motti10歡迎您。你也可以使用'String id = jb1.optString(「id」);' – Raghunandan