2016-01-19 106 views
0

我正在使用org.json解析器。 我得到一个使用jsonObject.getJSONArray(key)的json数组。 问题是jsonArray.length()回来了我1和我的json数组有2个元素,我做错了什么?jsonArray.length()没有给出数组元素的正确号码

String key= "contextResponses"; 
JSONObject jsonObject = new JSONObject(jsonInput); 
Object value = jsonObject.get("contextResponses"); 

if (value instanceof JSONArray){ 
    JSONArray jsonArray = (JSONArray) jsonObject.getJSONArray(key); 
    System.out.println("array length is: "+jsonArray.length());/*the result is 1! */ 
} 

这里是我的JSON:

{ 
    "contextResponses" : [ 
    { 
     "contextElement" : { 
     "type" : "ENTITY", 
     "isPattern" : "false", 
     "id" : "ENTITY3", 
     "attributes" : [ 
      { 
      "name" : "ATTR1", 
      "type" : "float", 
      "value" : "" 
      } 
     ] 
     }, 
     "statusCode" : { 
     "code" : "200", 
     "reasonPhrase" : "OK" 
     } 
    } 
    ] 
} 
+1

是,结果是'1'你能指望什么? –

回答

4

结果是完全正常的,因为JSONArray只包含一个JSONObject。要获得JSONObject你正在寻找的length,使用此:

// Get the number of keys stored within the first JSONObject of this JSONArray 
jsonArray.getJSONObject(0).length(); 

//---------------------------- 
{ 
    "contextResponses" : [ 
    // The first & only JSONObject of this JSONArray 
    { 
     // 2 JSONObjects 
     "contextElement" : { 
      // 1 
     }, 
     "statusCode" : { 
      // 2 
     } 
    } 
    ] 
} 
2

您的阵列只包含因此一个物体的长度是正确的:

"contextResponses" : [ 
    { 
    ... content of the object ... 
    } 
] 
相关问题