sabrina2020
sabrina2020

Reputation: 2472

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

Upvotes: 1

Views: 8108

Answers (2)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

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

Upvotes: 5

wero
wero

Reputation: 33000

Your array contains exactly one object therefore the length is correct:

"contextResponses" : [
  {
     ... content of the object ...
  }
]

Upvotes: 2

Related Questions