Using gson it is much simpler. Use following code snippet:

 // create a new Gson instance
 Gson gson = new Gson();
 // convert your list to json
 String jsonCartList = gson.toJson(cartList);
 // print your generated json
 System.out.println("jsonCartList: " + jsonCartList);

Converting back from JSON string to your Java object

 // Converts JSON string into a List of Product object
 Type type = new TypeToken<List<Product>>(){}.getType();
 List<Product> prodList = gson.fromJson(jsonCartList, type);

 // print your List<Product>
 System.out.println("prodList: " + prodList);
Answer from anubhava on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java list › converting a java list to a json array
Converting a Java List to a Json Array | Baeldung
June 18, 2025 - We aim to convert this “articles” list into a JSON array. So, the expected output should be as follows: ... We’ll explore three different approaches in the following sections to accomplish the conversion task. Gson is a popular Java library developed by Google for working with JSON data since it provides a simple API for converting Java objects to JSON. First of all, we need to add the Gson dependency to the pom.xml file:
🌐
Makeinjava
makeinjava.com › home › convert list of objects to/from json in java (jackson objectmapper/ example)
Convert list of objects to/from JSON in java (jackson objectmapper/example)
January 1, 2024 - Convert list of user defined objects or POJOs to JSON String - jackson objectmapper in java. Transformed List collections to JSON String (maven dependency)
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-an-arraylist-of-objects-to-a-json-array-in-java
How to Convert an ArrayList of Objects to a JSON Array in Java? - GeeksforGeeks
July 23, 2025 - Here we are adding the logic of converting an ArrayList of objects to a JSON array of Java in the main class. ... package org.example; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // Create an ArrayList of objects List<Course> courses = new ArrayList<>(); courses.add( new Course(1, "Java", "25000", "3 Months")); courses.add( new Course(2, "C++", "20000", "3 Months")); // Convert the ArrayList to a JSON array ObjectMapper objectMapper = new ObjectMapper(); try { String jsonArray = objectMapper.writeValueAsString(courses); System.out.println(jsonArray); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
🌐
Quora
quora.com › How-do-I-convert-a-list-to-JSON-in-Java
How to convert a list to JSON in Java - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-convert-a-list-to-the-json-array-in-java
How to convert a List to JSON array using the Jackson library in Java?
April 22, 2025 - <dependency> <groupid>com.fast... </dependency> The writeValueAsString() method of the ObjectMapper class serializes a given Java object, such as a List or ArrayList, into JSON-formatted String....
Find elsewhere
🌐
YouTube
youtube.com › watch
How To Convert Java List Object Into JSON String using Jackson API | Java Inspires - YouTube
In this video, we will see how to convert(serialize) Java List Object into JSON String and vice versa means how to convert(deserialize) JSON String to Java ...
Published: June 7, 2021
🌐
Java Guides
javaguides.net › 2019 › 07 › convert-list-to-json-array-using-jackson.html
Convert List to JSON Array Using Jackson
July 21, 2019 - In this quick article, I will show how to convert a List to JSON array using Jackson. Check out complete Jackson tutorial at Java Jackson JSON Tutorial with Examples. We are using Jackson library to convert Java List to JSON array so let's add below Jackson dependency to your project's classpath or pom.xml.
🌐
javathinking
javathinking.com › blog › convert-list-to-json-java-objectmapper
Converting a List to JSON in Java using ObjectMapper — javathinking.com
Then we create a list of Person objects. We instantiate an ObjectMapper object. Finally, we use the writeValueAsString() method to convert the list to a JSON string and print it. If your Java class does not have getters for its fields, ObjectMapper ...
🌐
QA Automation Expert
qaautomation.expert › 2023 › 11 › 10 › how-to-convert-a-java-list-to-json-array-org-json
How to convert a Java list to JSON Array – org.json
November 8, 2023 - Let us create a Java List. List<String> list = Arrays.asList("Test 1", "Test 2", "Test 3", "Test 4"); We want to convert this list in a JSON Object. Below is the sample code. import org.json.JSONArray; import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; public class ListToJsonObject { @Test public static void test() { List<String> list = Arrays.asList("Test 1", "Test 2", "Test 3", "Test 4"); System.out.println("List :" + list); JSONArray jsonArray = new JSONArray(list); System.out.println("Json Array :" + jsonArray); } }
Top answer
1 of 3
2

The problem is with your Users class. You appear to be expecting it to just pick up the fields, but I don't believe JSONObject does that - instead, it finds bean-like getters.

If you try to convert a single instance of your Users class to a JSONObject you get exactly the same result ({}) - this problem has nothing to do with trying to convert multiple instances. (It would be worth taking a lesson from this about diagnosing problems - always try to reduce the scope.)

As soon as you create a class with appropriate getters, it works fine. Sample code:

public final class User {
    private final String firstName;
    private final String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

import org.json.*;
import java.util.*;

class Test {
   public static void main(String [] args) throws Exception {
       User user = new User("Jon", "Skeet");
       JSONObject single = new JSONObject(user);
       System.out.println("Single user: " + single);

       Set<User> users = new HashSet<>();
       users.add(new User("Jon", "Skeet"));
       users.add(new User("Holly", "Skeet"));

       JSONObject multiple = new JSONObject();
       multiple.put("users", users);
       System.out.println("Multiple users: " + multiple);
   }
}

Output:

Single user: {"lastName":"Skeet","firstName":"Jon"}
Multiple users: {"users":[{"lastName":"Skeet","firstName":"Holly"},{"lastName":"Skeet","firstName":"Jon"}]}
2 of 3
1

I got correct result using the code below. Can you highlight if you are doing something different? Maybe I can make similar changes and try once.

public static void main(String[] args){
    HashSet<String> users = new HashSet<>(); 
    users.add("user1");
    users.add("user2");

    JSONObject j = new JSONObject();
    j.put("users", users);
    System.out.println(j.toString(2));        
}

Output:

{"users": [ "user2", "user1" ]}

================================== EDIT =================================

I think I figured what the problem was. Please try the following code and let us know if that worked.

public static void main(String[] args) {
    JSONObject o1 = new JSONObject();
    o1.put("1", new User("User1"));
    JSONObject o2 = new JSONObject();
    o2.put("2", new User("User2"));

    HashSet<JSONObject> users = new HashSet<>(); 
    users.add(o1);
    users.add(o2);

    JSONObject j = new JSONObject();
    j.put("users", users);
    System.out.println(j.toString(2));        
}
🌐
Crunchify
crunchify.com › json tutorials › in java how to convert arraylist to jsonobject?
In Java How to Convert ArrayList to JSONObject? • Crunchify
May 17, 2018 - Gson gson = gsonBuilder.create(); String JSONObject = gson.toJson(crunchify); log("\nConverted JSONObject ==> " + JSONObject); Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); String prettyJson = prettyGson.toJson(crunchify); log("\nPretty JSONObject ==> " + prettyJson); } private static void log(Object print) { System.out.println(print); } } Raw ArrayList ===> [Google, Facebook, Crunchify, Twitter, Snapchat, Microsoft] Converted JSONObject ==> ["Google","Facebook","Crunchify","Twitter","Snapchat","Microsoft"] Pretty JSONObject ==> [ "Google", "Facebook", "Crunchify", "Twitter", "Snapchat", "Microsoft" ] I hope you can use this simple utility to convert any Java Objects to JSONObject or JSONArray.
🌐
Mkyong
mkyong.com › home › java › how to parse json array with jackson
How to parse JSON Array with Jackson | mkyong.com
April 23, 2024 - package com.mkyong.json.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mkyong.json.model.Person; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsonArrayToObjectExample3 { public static void main(String[] args) throws JsonProcessingException { // Create a list of Person objects List<Person> people = Arrays.asList( new Person("mkyong", 42), new Person("ah pig", 20) ); // Wrap the list in a Map with "Person" as the key Map<String, List<Person>> wrapper
🌐
GitHub
gist.github.com › sheharyarn › cba56ff154de2cc62fc5
Simple Java Class to convert Lists/Maps to JSON and vice versa · GitHub
Simple Java Class to convert Lists/Maps to JSON and vice versa · Raw · SimpleJSON.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Kode Java
kodejava.org › how-do-i-convert-collections-into-json
How do I convert collections into JSON? - Learn Java by Examples
May 31, 2024 - package org.kodejava.gson; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.kodejava.gson.support.Student; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class CollectionToJson { public static void main(String[] args) { // Converts a collection of string object into JSON string. List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Carol"); names.add("Mallory"); Gson gson = new Gson(); String jsonNames = gson.toJson(names); System.out.p
🌐
GeeksforGeeks
geeksforgeeks.org › java › convert-an-arraylist-into-a-json-string-in-java
How to Convert an ArrayList into a JSON String in Java? - GeeksforGeeks
July 23, 2025 - Here we are adding the logic of converting an ArrayList into a JSON string of Java in the main class. ... package org.example; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create an ArrayList ArrayList<String> courses = new ArrayList<>(); courses.add("Java"); courses.add("Python"); courses.add("C++"); // Convert ArrayList to JSON string ObjectMapper objectMapper = new ObjectMapper(); try { String jsonString = objectMapper.writeValueAsString(courses); // Print JSON string System.out.println(jsonString); } catch (JsonProcessingException e) { e.printStackTrace(); } } }