0

Lets say I have a JSON array like this

[{"a":"1", "b":"2"}, {"c":"3", "d":"4"}]

I'm trying to get it in Java like this

JSONArray array = new JSONArray(responseBody); //resposeBody is the JSON array
for (int i = 0; i < array.length(); i++) {
    String arr = array.get(i).toString(); //Trying to get each array like this
    JSONArray json = new JSONArray(arr);
}

At the line of JSONArray json = new JSONArray(arr);I get the error

A JSONArray text must start with '['

How do I access the values?

EDIT: I mean how do I get each array and their values

1
  • Could you print out what's responseBody before calling JSONArray? Commented Dec 29, 2015 at 1:57

2 Answers 2

1

Your JSONArray is an array of JSONObjects. You can try

JSONArray array = new JSONArray(responseBody); 
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);  
}

Now you can further parse the individual JSONObjects.

Sign up to request clarification or add additional context in comments.

1 Comment

The fact you just told me my JSONArray is an array of JSONObjects made me solve my problem. This is my first time dealing with JSON with Java or even JSON itself. I'm able to access the keys and values now thank you
0

Just do :

JSONObject myJsonObject = new JSONObject(jsonString);

In array:

 JSONObject myjObject = myJsonArray.getJSONObject(i);

Comments

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.