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"));
Answer from Rob Tanzola on Stack Overflow
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();
🌐
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 ...
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonobject
org.json.JSONObject.put java code examples | Tabnine
June 27, 2019 - ArrayList<String> list = new ArrayList<String>(); list.add("john"); list.add("mat"); list.add("jason"); list.add("matthew"); JSONObject school = new JSONObject(); school.put("class","4"); school.put("name", new JSONArray(list)); ... @Override ...
🌐
Alex Arriaga
alex-arriaga.com › how-to-create-a-list-from-a-json-object-in-java-using-jackson
How to create a List from a JSON object in Java using Jackson Library – Alex Arriaga
January 21, 2014 - Let me show two single lines to map our JSON input into a Java List. // This is an example of a JSON input string String jsonString = "[{\"title\":\"Title of hotspot #1\",\"x\":194,\"y\":180,\"order\":0,\"url\":\"http://www.alex-arriaga.com/\"},{\"title\":\"Title of hotspot #2\",\"x\":23,\"y\":45,\"order\":1,\"url\":\"http://www.alex-arriaga.com/about-me/\"}]"; try{ ObjectMapper jsonMapper = new ObjectMapper(); List <HotSpot> hotspots = jsonMapper.readValue(jsonString, new TypeReference<List<HotSpot>>(){}); }catch(Exception e){ e.printStackTrace(); }
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-add-elements-to-json-object-using-json-lib-api-in-java
How to add elements to JSON Object using JSON-lib API in Java?
public JSONObject element(String key, Object value) - put a key/value pair in the JSONObject · import java.util.Arrays; import net.sf.json.JSONObject; public class JsonAddElementTest { public static void main(String[] args) { JSONObject jsonObj = new JSONObject() .element("name", "Raja Ramesh") .element("age", 30) .element("address", "Hyderabad") .element("contact numbers", Arrays.asList("9959984000", "7702144400", "7013536200")); System.out.println(jsonObj.toString(3)); //pretty print JSON } }
Find elsewhere
Top answer
1 of 2
25

You can use the putArray method which creates an ArrayNode. Then you should fill it with the elements from your list.

ArrayNode arrayNode = row.putArray("myList");
for (String item : list) {
    arrayNode.add(item);
}
2 of 2
0

Here is a functional way of creating an arrayNode and populate it elements from a stream. It does the same as above fracz answer :

    yourStringList.stream()
        .collect(Collector.of(
            () -> row.putArray("myList"), 
            (arrayNode, item) -> arrayNode.add(item), 
            (arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2);  return arrayNode1; },
            Collector.Characteristics.IDENTITY_FINISH
        ));

Essentially, it defines a custom collector to accumulate the elements provided by the stream. Some explanations:

  • the first argument () -> row.putArray("myList") defines the function which will provide the object to accumulate the items (called the supplier function). In our case this function will provide the ArrayNode and is the equivalent of ArrayNode arrayNode = row.putArray("myList"); statement in the above answer.
  • the second argument (arrayNode, item) -> arrayNode.add(item) defines the accumulator function whose role is to add the elements. In the left side of the -> operator, the first variable (e.g. arrayNode) refers to the container defined in the first argument while the second (e.g. item) refers to the element to accumulate provided by the stream. This function does the same job as the statement arrayNode.add(item); inside the loop in the above example.
  • the third argument (arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2); return arrayNode1; } is the combiner function which is used if the stream is collected in parralel (for instance if we had .parralelStream() instead of .stream()). Its role is to merge two accumulators toghether and this is why the function has two argumets of the same type. We define this function such that it will add all elements accumulated in the second accumulator into the first accumulator and return this first accumulator.
  • the fourth argument Collector.Characteristics.IDENTITY_FINISH define one or more optons to the process. In this case, IDENTITY_FINISH simply states that no finisher function will be provided (to further process the accumulator object) or, in other words, that the finisher function is the identity function (no treatment done).

This solution might seems more complex at first but it leverages all the power of functionnal programming. For instance, we could stream objects, extract a String property with the map function, filter it, etc. before collecting everything:

    yourObjectList.stream()
        .map(o -> o.getTheStringProperty())
        .filter(o -> o.length() > MIN_SIZE)
        .collect(Collector.of(
            () -> row.putArray("myList"), 
            (arrayNode, item) -> arrayNode.add(item), 
            (arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2);  return arrayNode1; },
            Collector.Characteristics.IDENTITY_FINISH
        ));
🌐
Coderanch
coderanch.com › t › 643753 › java › Create-Json-List-data
Create Json from a List's data (EJB and other Jakarta /Java EE Technologies forum at Coderanch)
All these names though are retrieved from the DB and held in Lists. My first reaction was to iterate the Lists, after specifying an ArrayBuilder outside the loop, and add these objects. Problem is it doesn't work. Either I don't add the elements correctly or it doesn't write the output correctly. How would you write a similar Json iterating a List? Netbeans 11 - JavaEE ...
Top answer
1 of 2
2

Iterate through the list in reverse and upon each iteration create a new JsonNode for the list element, add the previous JsonNode as a child to the new JsonNode and overwrite the original reference with the new JsonNode. Rinse and repeat.

Something like...

final String value = "BMW"; // whatever the final "value" is.
final ObjectMapper objectMapper = new ObjectMapper();

ObjectNode json = null;

for (int i = list.size() - 1; i >= 0; i--) {

  final String prop = list.get(i);
  final ObjectNode objectNode = objectMapper.createObjectNode();

  if (json == null) {
    objectNode.put(prop, value);
  } else {
    objectNode.put(prop, json);
  }

  json = objectNode;
}
2 of 2
-1

Here is the piece of code which you need

package uk.co.vishal;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Answer {

public static void main(String[] args) throws JsonProcessingException {
    List<String> data = new ArrayList<>();
    data.add("user");
    data.add("car");
    data.add("brand");

    System.out.println(data.toString());

    Map<String, String> mydata = new HashMap<>();
    Map<String, JSONObject> newdata = new HashMap<>();
    JSONObject result = new JSONObject();
    boolean flag = true;

    for (int i = data.size() - 1; i >= 0; i--) {
        if (flag) {
            mydata.put(data.get(i), "BMW");
            result = generateJson(mydata);
            flag = false;
        } else {
            newdata.put(data.get(i), result);
            result = generateJson(newdata);
            newdata.clear();
        }
    }
    System.out.println(result);
    /*
    * Here is the output:
    * {
        "user": {
            "car": {
                    "brand": "BMW"
                }
            }
      }
    *
    * */
}

private static JSONObject generateJson(Map data) {
    return new JSONObject(data);
}

}

I hope you will be sorted !!

🌐
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 - We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method. import org.json.*; import java.util.*; public class AddJSONArrayToJSONObjTest { public static void main(String args[]) ...
🌐
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 - Move JSONObject EdgeJsonObjsub = new JSONObject(); inside the loop where you are building the JSON structure.
🌐
Attacomsian
attacomsian.com › blog › jackson-convert-json-array-to-from-java-list
Convert JSON array to a list using Jackson in Java
November 6, 2022 - Now we can use the readValue() method from the ObjectMapper class to transform the above JSON array to a list of User objects, as shown below: try { // JSON array String json = "[{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"," + ...
🌐
Stack Overflow
stackoverflow.com › questions › 40463812 › add-list-of-objects-in-jsonobject-in-java
json - Add list of objects in JsonObject in java - Stack Overflow
November 7, 2016 - JSONObject json = new JSONObject(); json.accumulate("abz", "xyz").append("sample", data); System.out.println(json.toString()); ... The question is about javax.json.JsonObject, which is not the same thing as JSONObject.