1

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"
      }
    }
  ]
}
1
  • 1
    Yes, the result is 1 what do you expect? Commented Jan 19, 2016 at 11:07

2 Answers 2

5

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
      }
    }
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.