Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:

List<JSONObject> list = new ArrayList<JSONObject>();
try {
    int i;
    JSONArray array = new JSONArray(string);
    for (i = 0; i < array.length(); i++)
        list.add(array.getJSONObject(i);
} catch (JSONException e) {
    System.out.println(e.getMessage());
}
Answer from Victor Dodon on Stack Overflow
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONObject.html
JSONObject
Produce a JSONArray containing the values of the members of this JSONObject. ... names - A JSONArray containing a list of key strings.
Discussions

How to parse json to get size of the list from jsonObject using Java?
Google "How to parse JSON Java" will return plenty of guides - more useful and a larger resources then what a reddit comment can provide :) Most parsing libraries use common Java structures, so if the json object contains a list, then the list will most likely have a "size" method you can use. More on reddit.com
🌐 r/softwaretesting
20
2
May 16, 2022
json - How to put a List into a JSONObject and then read that object in Java? - Stack Overflow
I have a List that I would like to convert into a JSON object and then traverse the data out of the JSON object. If this were just a List I could just do something like: More on stackoverflow.com
🌐 stackoverflow.com
java - JSON: Get list of JSON Objects - Stack Overflow
For more info, please refer to the docs on JSONArray and JSONObject. More on stackoverflow.com
🌐 stackoverflow.com
arrays - How to get a value which is a List from a JSONObject in Java - Stack Overflow
JSONObject json = new JSONObject(); List list = new ArrayList(); ... // adding data in json ... list = (List) json.get("data"); This is not working. ... Sign up to request clarification or add additional context in comments. ... I don't quite uderstand the syntax. I have this error: org.json.JSONArray cannot be cast to java... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › @papapapaya11 › exploring-various-ways-to-handle-jsonobject-in-java-6edef1f0561c
Exploring Various Ways to Handle JSONObject in Java | by Little Miss Brave | Medium
December 2, 2024 - String json = "{\"name\":\"Little ... // ["Little Miss Brave","Amy","Mandy"] Overview: A straightforward and simple library for creating and parsing JSON data....
🌐
Reddit
reddit.com › r/softwaretesting › how to parse json to get size of the list from jsonobject using java?
r/softwaretesting on Reddit: How to parse json to get size of the list from jsonObject using Java?
May 16, 2022 -

Hi, All,

I am facing problem while parsing json tried different ways to parse json ending up with error. I actually want to get the size of list present in jsonObject so that I can run a for loop till that size and get attributes accordingly.

Running to the error - org.json.JSONException : A JSONArray text must start with '[' at 1 [character 2 line 1]

Json is present on the below link :

https://reqres.in/api/users?page=2

Can you guys please help me with different code snippet how can it be achieved? Will be very thankful to you all.

Top answer
1 of 5
20

Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.

For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):

JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();

SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);

SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);

obj.put("list", sList);

JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
  System.out.println(jArray.getJSONObject(ii).getString("value"));
2 of 5
3

Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();

    //if List not empty
    if (!(sList.size() ==0)) {

        //Loop index size()
        for(int index = 0; index < sList.size(); index++) {
            JSONObject eachData = new JSONObject();
            try {
                eachData.put("name", sList.get(index).getName());
                eachData.put("dob", sList.get(index).getDob());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            allDataArray.put(eachData);
        }
    } else {
        //Do something when sList is empty
    }
    

Finally, add the JSONArray to a JSONObject.

JSONObject root = new JSONObject();
    try {
        root.put("data", allDataArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

You can further get this data as a String too.

String jsonString = root.toString();
Find elsewhere
🌐
How to do in Java
howtodoinjava.com › home › convert json array to list: gson, jackson and org.json
Convert JSON Array to List: Gson, Jackson and Org.json
September 25, 2023 - The following code parses a JSON array containing person data and converts it into a list of Java Person objects using the JSONArray and JSONObject classes.
🌐
GitHub
github.com › stleary › JSON-java › issues › 491
Casting list of JSONObject to JSONObject throws ClassCastException · Issue #491 · stleary/JSON-java
October 22, 2019 - @Test public void shouldCastArrayOfJSONObjectsToList() { String a = "{\"a\": 1}"; String b = "{\"b\":2}"; String jsonString = "{\"list\":[" + a + "," + b + "]}"; JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("list"); List<JSONObject> jsonObjects = Lists.newArrayList(jsonArray.iterator()).stream().map(JSONObject.class::cast).collect(Collectors.toList()); assertEquals(jsonObjects.size(), 2); }
Author   ggavriilidis
🌐
Coderanch
coderanch.com › t › 713115 › java › conversion-array-list-Json-object
conversion of array list to Json object string (Java in General forum at Coderanch)
July 19, 2019 - Hi I have two lists Edge1List and Edge2List which I add to element on them. Edge1List:[o,p] and Edge2List: [p,null]. I convert Edge1List and Edge2List to JsonArray with the name of EdgeJsonArray1 and EdgeJsonArray2 respectively. I want to show that o from EdgeJsonArray1 is connect to p from EdgeJsonArray2 and p from EdgeJsonArray1 is connected to null from EdgeJsonArray2 which is I put them in a Jsonobject name as EdgeJsonObjsub with different key.
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonarray
org.json.JSONArray.getJSONObject java code examples | Tabnine
JSONArray array; for(int n = 0; n < array.length(); n++) { JSONObject object = array.getJSONObject(n); // do some stuff.... } ... List<Photo> parse(String response) throws JSONException { JSONObject searchResults = new JSONObject(response.substring(FLICKR_API_PREFIX_LENGTH, response.length() - 1)); JSONArray photos = searchResults.getJSONObject("photos").getJSONArray("photo"); List<Photo> results = new ArrayList<>(photos.length()); for (int i = 0, size = photos.length(); i < size; i++) { results.add(new Photo(photos.getJSONObject(i))); } return results; } }
Top answer
1 of 2
3

If anyone else is stuck here, It turned out I was on the right track, I can access the List using getJSONArray, but when iterating for each member, I use getString

 public static Person parsePersonJson(String json) {

            JSONObject currentPerson;
            String name;

            try {
                currentPerson = new JSONObject(json);

                // so I can access the name like

                name = currentPerson.getString("name");

                List<String> alsoKnownAs= new ArrayList<>();

                //use getJSONArray to get the list

                JSONArray arrayKnownAs = currentPerson.getJSONArray("alsoKnownAs");

                for (int i = 0, l = arrayKnownAs.length(); i < l; i++) {

                 //This is where I was getting it wrong, i needed to use getString to access list items

                  alsoKnownAs.add(arrayKnownAs.getString(i));
                   }



               Person thisPerson =  new Person(

                //I instantiate person object here

                );
                return thisPerson;

            } catch (org.json.JSONException e) {
             // error
            }
            return null;
        }
2 of 2
2

Here a solution using com.fasterxml.jackson

Person.java:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

class Person  {
    final public String name;
    final public List<String> alsoKnownAs;

    @JsonCreator
    public Person(
            @JsonProperty("name") final String name,
            @JsonProperty("alsoKnownAs") final List<String> alsoKnownAs
    ) {
        this.name = name;
        this.alsoKnownAs = alsoKnownAs;
    }

    public static Person parsePersonJson(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, Person.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Here a quick test:

PersonTest.java

import org.junit.Test;

public class PersonTest {


    @Test
    public void parseAJsonToAPerson() {
        String json = "{\"name\":\"moses\",\"alsoKnownAs\":[\"njai\", \"njenga\",\"musa\"]}";
        Person currentPerson = Person.parsePersonJson(json);

        System.out.println("name: " + currentPerson.name);
        System.out.println("alsoKnownAs: " + currentPerson.alsoKnownAs);

    }

}

Test output is:

name: moses
alsoKnownAs: [njai, njenga, musa]
🌐
Baeldung
baeldung.com › home › json › jackson › convert json array to java list
Convert JSON Array to Java List | Baeldung
August 13, 2025 - Then, we use the readValue() method of the ObjectMapper object to convert the JSON array String to a List. Similar to the assertion discussed previously, finally, we compare a specific field from the String JSON array to the jacksonList ...
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonObject.html
JsonObject (Java(TM) EE 7 Specification APIs)
javax.json · All Superinterfaces: JsonStructure, JsonValue, Map<String,JsonValue> public interface JsonObject extends JsonStructure, Map<String,JsonValue> JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs).
🌐
Mkyong
mkyong.com › home › java › how to parse json array with jackson
How to parse JSON Array with Jackson - Mkyong.com
April 23, 2024 - convert JSON array to Array objects Person[] person1 = mapper.readValue(jsonArray, Person[].class); for (Person p : person1) { System.out.println(p); } // 2. convert JSON array to List List<Person> person2 = mapper.readValue(jsonArray, new TypeReference<>() { }); person2.forEach(System.out::println); } } ... Person{name='mkyong', age=42} Person{name='ah pig', age=20} Person{name='mkyong', age=42} Person{name='ah pig', age=20} ... package com.mkyong.json.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mkyong.json
🌐
Stack Overflow
stackoverflow.com › questions › 31734264 › converting-jsonobject-to-object-list
java - converting JSONObject to Object list - Stack Overflow
May 22, 2017 - public class GsonTest { public static void main(String[] args) { Gson gson = new Gson(); Object obj; try { JsonParser parser = new JsonParser(); obj = parser.parse(new FileReader("C:\data.json")); JsonObject jsonObject = (JsonObject) obj; Data data = gson.fromJson(jsonObject, Data.class); } catch (JsonIOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonSyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-convert-a-json-array-to-a-list-using-jackson-in-java
How can we convert a JSON array to a list using Jackson in Java?\\n
June 5, 2025 - import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.io.IOException; import java.util.ArrayList; public class JsonArrayToList{ public static void main(String[] args) { String jsonArray = "[{"name":"John","age":30},{"name":"Jane","age":25}]"; ObjectMapper objectMapper = new ObjectMapper(); try { List<Person> personList = objectMapper.readValue(jsonArray, new TypeReference<List<Person>>(){}); for (Person person : personList) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge()); } }
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-add-a-jsonarray-to-jsonobject-in-java
How can we add a JSONArray to JSONObject in Java?
July 4, 2020 - import org.json.*; import java.util.*; public class AddJSONArrayToJSONObjTest { public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add("Raja"); list.add("Jai"); list.add("Adithya"); JSONArray array = new JSONArray(); for(int i = 0; i < list.size(); i++) { array.put(list.get(i)); } JSONObject obj = new JSONObject(); try { obj.put("Employee Names:", array); } catch(JSONException e) { e.printStackTrace(); } System.out.println(obj.toString()); } } {"Employee Names:":["Raja","Jai","Adithya"]} raja ·