Search code examples
javajsonorg.json

jsonArray.length() not given the right number of array element


I am using org.json parser. I am getting a json array using jsonObject.getJSONArray(key). The problem is the jsonArray.length() is returning me 1 and my json array have 2 elements, what am I doing wrong?

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! */
}

Here is my json:

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

Solution

  • The result is perfectly normal, since the JSONArray contains only one JSONObject. To get the length of the JSONObject you're looking for, use this:

    // 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
          }
        }
      ]
    }