0

I'm trying to simply parse a JSON array with the Java JSON library from json.org. The JSON I retrieve from the server is a JSON array and has the following structure:

[
    {
        "a": "u",
        "b": "v"
    },
    {
        "a": "x",
        "b": "y"
    }
]

To parse it, I use this simple instruction:

JSONArray jsonArray = new JSONArray(result);

for(int i=0; i<jsonArray.length(); i++) {

   JSONObject jsonObject = jsonArray.getJSONObject(i);
   //further processing here

}

This should work fine, but I get this error on execution:

JSONArray[0] is not a JSONObject.

In an attempt to solve this, I printed the JSONArray object using its toString() implementation and I get this:

["[{"a":"u","b":"v"},{"a":"x","b":"y"}]"]

So strangely enough, the JSONArray(String string) method adds [""] around the provided JSON... Hence the previous error, as the first child of the array is a String. How could I solve this?

Note that I use the latest version of the json.org library (November 13th 2014). I used it before in Android applications and I never met this problem. If possible, I'd like not to use another library.

  • why do you think the `toString()` representation has anything to do with this? Have you used a step debugger to see what the object really is represented by in memory? –  Nov 24 '14 at 17:57
  • The toString() method prints the exact JSON representation of the JSONArray (http://www.json.org/javadoc/org/json/JSONArray.html#toString()). I've checked the type of the first child of the JSONArray and it is indeed a String, instead of an expected JSONObject. So I'm afraid the "duplicate" question you suggest doesn't help Jarrod. – Christophe Longeanie Nov 25 '14 at 09:16
  • Just found where the error was coming from. The `result` variable containing the JSON was actually an **array** of Strings (from a "varargs" argument) and not a String. Therefore, doing `new JSONArray(result[0])` works. The JSONArray class has constructors both for a String and an Object argument, and I was calling the `JSONArray(Object obj)` constructor while thinking that `JSONArray(String str)` was being used. – Christophe Longeanie Nov 26 '14 at 15:42

0 Answers0