Tanishq dubey
Tanishq dubey

Reputation: 1542

Parse JSON Array without Key in Android

How would I parse an array like the following in Android?

[
 5,
 10,
 15,
 20
]

As you can see, there is no key defining the array, like other example arrays have, such as this:

{
 "items": [
   5,
   10,
   15
   ]
}

For the second array, I can easily make a JSONObject and just use:

JSONArray itemArray = jsonObject.getJSONArray("items")

But, as is obvious, there is no key for the first array. So how would one go about this? Is it even possible with standard Android libraries?

Upvotes: 18

Views: 30759

Answers (3)

Anand Saggam
Anand Saggam

Reputation: 57

Here you can directly access the data in json array.

JSONArray itemArray = jsonObject.getJSONArray("items");

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

{

int i = Integer.ParseInt(itemarray.get(i));

Log.i("Value is:::",""+i);

}

Upvotes: -2

Bidhan
Bidhan

Reputation: 10697

Have you tried doing this?

try {
    // jsonString is a string variable that holds the JSON 
    JSONArray itemArray=new JSONArray(jsonString);
    for (int i = 0; i < itemArray.length(); i++) {
        int value=itemArray.getInt(i);
        Log.e("json", i+"="+value);
    }
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: 24

Julien Leray
Julien Leray

Reputation: 1687

Consider Foreach version:

try {
    JSONArray itemArray=jsonObject.getJSONArray("items");
    for (var item : itemArray) {
        System.out.println(item);
    }
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: -2

Related Questions