简体   繁体   中英

How to access key:values in JSON using Java with no array names

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

Just do :

JSONObject myJsonObject = new JSONObject(jsonString);

In array:

 JSONObject myjObject = myJsonArray.getJSONObject(i);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM