18

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?

4
  • had you found the solution ? Commented Jun 12, 2020 at 9:03
  • Yep, the accepted answer has it: stackoverflow.com/a/30586115/2676875 Commented Jun 12, 2020 at 18:11
  • How can i implement this with retrofit Can you please help Commented Jun 13, 2020 at 13:28
  • I would open a new question for the specific use case of retrofit Commented Jun 16, 2020 at 14:34

3 Answers 3

24

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

3 Comments

Would this not parse the second JSON file? I apologize if my question was written in a confusing way. I want to parse the first JSON file, the one without the "items" key. Would this mean that my JSONArray would just be set to the JSON file that I am getting?
Yes, this would parse the second JSON file. I'm sorry I didn't understand your question. To get the first JSONArray, you would do something like JSONArray itemArray=new JSONArray(yourstringname); where yourstringname is a String variable that holds your JSON file(I'm assuming it's a string) and then the rest will be the same.
Perfect, just tried it and it works as intended. If you wouldn't mind, could you modify your answer so it matches the question for future readers/reference? I'll accept it after that.
-2

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();
}

Comments

-2

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

}

1 Comment

read the question again, response with no key need to be handles here.

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.