JSON String of Array to/from List of Java (Jackson)

Maven dependency of Jackson JSON Library

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.16.1</version>
</dependency>

Convert JSON String of Array to/from List of Java Objects (Jackson):

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

class Bus {
    public String model;
    public int capacity;

    @Override
    public String toString() {
        return "Bus{" +
                "model='" + model + '\'' +
                ", capacity=" + capacity +
                '}';
    }
}


public class JackListObjectToJSON {
    public static void main(String[] args) {
        // JSON array representing a list of Bus objects
        String jsonArrayString = "[
                      {\"model\":\"Volvo\",\"capacity\":50},
                      {\"model\":\"Mercedes\",\"capacity\":30}]";

        // Create ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // Convert JSON Array to List of Bus Objects
            List<Bus> busList = objectMapper.readValue(
                    jsonArrayString,
                    new TypeReference<List<Bus>>() {
                    }
            );

            // Access the List of Bus Objects
            System.out.println("JSON String to List of Java Objects:");
            for (Bus bus : busList) {
                System.out.println(bus);
            }

            System.out.println("\nList of Java Objects to JSON String:");
            jsonArrayString = objectMapper.writeValueAsString(busList);
            System.out.println(jsonArrayString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

JSON String to List of Java Objects:
Bus{model='Volvo', capacity=50}
Bus{model='Mercedes', capacity=30}

List of Java Objects to JSON String:
[{"model":"Volvo","capacity":50},{"model":"Mercedes","capacity":30}]
Scroll to Top