Convert String to JSONArray (not JsonArray from gson)

android, java, json

Solution

Try this :

JSONObject jObject = new JSONObject(STRING_FROM_ABOVE);
JSONArray jArray = jObject.getJSONArray("myArray");

The "string_from_above" is not a Json Array, it's a Json object, containing one attribute (myArray) which is a Json Array ;)

You can then do :

for (int i = 0; i < jArray.length(); i++) {
        JSONObject jObj = jArray.getJSONObject(i);
        System.out.println(i + " id : " + jObj.getInt("id"));
        System.out.println(i + " att1 : " + jObj.getDouble("att1"));
        System.out.println(i + " att2 : " + jObj.getBoolean("att2"));
}

Problem

how to properly convert this String to a jsonArray? ``` { "myArray": [ { "id": 1, "att1": 14.2, "att2": false }, { "id": 2, "att1": 13.2, "att2": false }, { "id": 3, "att1": 13, "att2": false } ]} ``` An `JSONArray jArray = new JSONArray(STRING_FROM_ABOVE);` results in `jArray.length = 1` Its my first time to get in touch with json :)

Original source

Related problems