1

我正在使用 org.json 解析器。我正在使用 json 数组jsonObject.getJSONArray(key)。问题是jsonArray.length()返回我1,我的 json 数组有 2 个元素,我做错了什么?

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"
      }
    }
  ]
}
4

2 回答 2

5

结果是完全正常的,因为JSONArray仅包含一个JSONObject。要获得lengthJSONObject正在寻找的,请使用:

// 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
      }
    }
  ]
}
于 2016-01-19T10:49:18.227 回答
2

您的数组只包含一个对象,因此长度是正确的:

"contextResponses" : [
  {
     ... content of the object ...
  }
]
于 2016-01-19T10:49:15.143 回答