jsonArray.length() 没有给出正确数量的数组元素

sab*_*020 1 java json org.json

我正在使用 org.json 解析器。我正在使用 .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! */
}
Run Code Online (Sandbox Code Playgroud)

这是我的json:

{
  "contextResponses" : [
    {
      "contextElement" : {
        "type" : "ENTITY",
        "isPattern" : "false",
        "id" : "ENTITY3",
        "attributes" : [
          {
            "name" : "ATTR1",
            "type" : "float",
            "value" : ""
          }
        ]
      },
      "statusCode" : {
        "code" : "200",
        "reasonPhrase" : "OK"
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*uag 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
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)