2015-07-21 65 views
-1

對不起,我的英語。我試着解析插入的json,在我的例子中我有這個json:解析插入的json對象android

{ 
    "myTable": { 
     "1": { 
      "type": "1", 
      "category": "1", 
      "body": { 
       "2": { 
        "id": "2", 
        "device_name": "test 1" 
       }, 
       "5": { 
        "id": "5", 
        "device_name": "test 2" 
       } 
      } 
     }, 
     "2": { 
      "type": "2", 
      "category": "1", 
      "body": { 
       "6": { 
        "id": "6", 
        "device_name": "test 3" 
       } 
      } 
     } 
    } 
} 

它的json對象爲json對象。這讓我難倒了。婁我try代碼解析此JSON

JSONObject sensorTypes = json.getJSONObject("myTable"); 

       if(sensorTypes.length() > 0) { 
        Iterator<String> iterasensorTypes = sensorTypes.keys(); 

        while(iterasensorTypes.hasNext()) { 
         String currentKey = iterasensorTypes.next(); 
         JSONObject obj = sensorTypes.optJSONObject(currentKey); 

         if(obj != null) { 
          Log.e("type", obj.getString("type")); 
          Log.e("category", obj.getString("category")); 

          JSONObject sensor = json.getJSONObject("body"); 
          if(sensor.length() > 0) { 
           Iterator<String> iteratorSensor = sensor.keys(); 

           while(iteratorSensor.hasNext()) { 
            String currentKeySensor = iteratorSensor.next(); 
            JSONObject objSensor = sensor.optJSONObject(currentKeySensor); 

            if(objSensor != null) { 
             Log.e("device_name", objSensor.getString("device_name")); 
            } 
           } 
          } 
         } 


        } 

       } 

,我有這樣的:

org.json.JSONException:

我的日誌:

body

UPD沒有價值

E/type﹕ 1 E/category﹕ 1 E/ get﹕ org.json.JSONException: No value for body 
+0

後的你的全'log' – Pankaj

+0

@Clairvoyant感謝爲了回答,我更新了我的問題 – g6848453

回答

0

你是usi ng json.getJSONObject("body");而不是obj.getJSONObject("body");,json是頂部的對象,其中一個用鍵myTablebodymyTable的孩子裏面,那些你通過迭代,並使用參考obj對象JSONObject obj = sensorTypes.optJSONObject(currentKey);

+1

啊...謝謝,愚蠢的錯誤。感謝它的工作 – g6848453

0

相反

JSONObject sensor = json.getJSONObject("body"); 

使用

JSONObject sensor = obj.getJSONObject("body"); //changed to obj from json