Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to JSONArray (not JsonArray from gson) [duplicate]

Tags:

java

json

android

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 :)

like image 291
DieselPower Avatar asked Aug 13 '13 15:08

DieselPower


1 Answers

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"));
}
like image 125
Organ Avatar answered Sep 23 '22 18:09

Organ