There's no built-in way to do this. You'll have to write your own JsonSerializer. Something like

class ModelSerializer extends JsonSerializer<List<Model>> {

    @Override
    public void serialize(List<Model> value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException {
        jgen.writeStartArray();
        for (Model model : value) {
            jgen.writeStartObject();
            jgen.writeObjectField("model", model);
            jgen.writeEndObject();    
        }
        jgen.writeEndArray();
    }

}

and then annotate the models field so that it uses it

@JsonSerialize(using = ModelSerializer.class)
private List<Model> models;

This would serialize as

{
    "status": "success",
    "models": [
        {
            "model": {
                "id": 1,
                "color": "red"
            }
        },
        {
            "model": {
                "id": 2,
                "color": "green"
            }
        }
    ]
}

If you're both serializing and deserializing this, you'll need a custom deserializer as well.

Answer from Sotirios Delimanolis on Stack Overflow
🌐
Medium
cowtowncoder.medium.com › jackson-tips-custom-list-serialization-4566f734c58d
Jackson Tips: custom List serialization | by @cowtowncoder | Medium
May 31, 2021 - Which is probably the most often reported issue that is due to limitations imposed by Java Type Erasure. What happens when attempting to serialize a List<Animal> instance is that JDK at runtime has no real knowledge of intended generic type: all you can see from instance is that it is a List<?> ; which is about same as List<Object> as far as Jackson knows — and java.lang.Object is not a polymorphic type.
Top answer
1 of 3
37

There's no built-in way to do this. You'll have to write your own JsonSerializer. Something like

class ModelSerializer extends JsonSerializer<List<Model>> {

    @Override
    public void serialize(List<Model> value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException {
        jgen.writeStartArray();
        for (Model model : value) {
            jgen.writeStartObject();
            jgen.writeObjectField("model", model);
            jgen.writeEndObject();    
        }
        jgen.writeEndArray();
    }

}

and then annotate the models field so that it uses it

@JsonSerialize(using = ModelSerializer.class)
private List<Model> models;

This would serialize as

{
    "status": "success",
    "models": [
        {
            "model": {
                "id": 1,
                "color": "red"
            }
        },
        {
            "model": {
                "id": 2,
                "color": "green"
            }
        }
    ]
}

If you're both serializing and deserializing this, you'll need a custom deserializer as well.

2 of 3
4

This is an oldish question, But there is an arguably more idiomatic way of implementing this (I'm using jackson-databind:2.8.8):

Define a ModelSerializer (That extends StdSerializer as recommended by Jackson) that prints your model how you like and use the @JsonSerialize(contentUsing = ...) over your collection type:

class ModelSerializer extends StdSerializer<Model> {

    public ModelSerializer(){this(null);}
    public ModelSerializer(Class<Model> t){super(t);} // sets `handledType` to the provided class

    @Override
    public void serialize(List<Model> value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeObjectField("model", value);
        jgen.writeEndObject();
    }
}

Meanwhile, in another file:

class SomethingWithModels {
    // ...
    @JsonSerialize(contentUsing = ModelSerializer.class)
    private Collection<Model> models;
    // ...
}

Now you aren't bound to just Lists of models but may apply this to Collections, Sets, Native []s and even the values of Maps.

Discussions

json - Java+Jackson : How to serialize a object containing array/list of other objects - Stack Overflow
The above json is a query body ... of content object or data model. I am getting this exception while serializing the object: com.fasterxml.jackson.core.JsonGenerationException: Can not start an object, expecting field name at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1886) at ... More on stackoverflow.com
🌐 stackoverflow.com
java - How do I serialize a list of objects with Jackson? - Stack Overflow
I have a class A that I created a custom serializer for. Class B has a member variable private List as; and some other members with Double as the data type. What do I have to do to serialize/ More on stackoverflow.com
🌐 stackoverflow.com
January 8, 2021
java - How to serialize and deserialize a list of objects using Jackson - Stack Overflow
Seems like your JSON represents an object, and you're trying to deserialize it as an array. ... Impossible to tell without you providing a MVCE. ... There is obviously a problem with your JSON, why don't you serialize your array of Restaurants and see how it should like? More on stackoverflow.com
🌐 stackoverflow.com
June 11, 2019
json - Jackson - Serialize only Ids of objects in a list attribute of a Java Pojo - Stack Overflow
I want to optimize the json data to be sent on wire. I have three models in my code. These are Customer, Invoice and Particular. The Customer class @Data public class Customer implements Serializ... More on stackoverflow.com
🌐 stackoverflow.com
March 22, 2019
🌐
Studytrails
studytrails.com › 2016 › 09 › 12 › java-jackson-serialization-list
Java json – jackson List serialization – Studytrails
We use the ObjectMapper class to do the serialization and print the json to console. You could also print it to a file · package com.studytrails.json.jackson; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonGenerationException; ...
🌐
Java Guides
javaguides.net › 2019 › 04 › jackson-list-set-and-map-serialization-and-deseialization-in-java-example.html
Jackson - List, Set and Map Serialization and Deserialization in Java Examples
April 24, 2019 - ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); List < String > progLangs = new ArrayList < > (); progLangs.add("C"); progLangs.add("C++"); progLangs.add("Java"); progLangs.add("Java EE"); progLangs.add("Python"); progLangs.add("Scala"); progLangs.add("JavaScript"); // Serialize Object to JSON. String json = mapper.writeValueAsString(progLangs); // Print json System.out.println(json); } } ... Let's demonstrates how to convert a Set object to JSON is using the ObjectMapper.writeValueAsString() method. package net.javaguides.jackson; import java.util.
🌐
Mosy
thepracticaldeveloper.com › java-and-json-jackson-serialization-with-objectmapper
Java and JSON – Jackson Serialization with ObjectMapper | Mosy
July 31, 2018 - You can alter this behavior with annotations or custom serializers. In this example, PersonName is used as a wrapper for a simple String. A list of Java objects gets serialized to a list of JSON objects containing the fields and their values.
🌐
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 - package org.learn; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JSONListConverter { public static void main( String[] args ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); //Define map which will be converted to JSON List<Person> personList = Stream.of( new Person("Mike", "harvey", 34), new Person("Nick", "young", 75), new Person("Jack", "slater", 21 ), new Person("gary", "hudson", 55)) .collect(Collectors.toList()); //1.
🌐
Oracle
blogs.oracle.com › javamagazine › java-json-serialization-jackson
Looking for a fast, efficient way to serialize and share Java objects? Try Jackson.
This means that if your objects depend on Java 8 APIs directly (such as classes from java.time), the serialization must use a specific Java 8 module (JavaTimeModule). This class must be registered when the mapper is created—it is not available by default. To handle that requirement, you will also need to add a couple of extra dependencies to the Jackson libraries’ default.
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – unmarshall to collection/array
Jackson - Unmarshall to Collection/Array | Baeldung
April 26, 2024 - Reading the same JSON Array into a Java Collection is a bit more difficult – by default, Jackson will not be able to get the full generic type information and will instead create a collection of LinkedHashMap instances: @Test public void givenJsonArray_whenDeserializingAsListWithNoTypeInfo_thenNotCorrect() throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); List<MyDto> listOfDtos = Lists.newArrayList( new MyDto("a", 1, true), new MyDto("bc", 3, false)); String jsonArray = mapper.writeValueAsString(listOfDtos); List<MyDto> asList = mapper.readValue(jsonArray, List.class); assertThat((Object) asList.get(0), instanceOf(LinkedHashMap.class)); }
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 42087229 › javajackson-how-to-serialize-a-object-containing-array-list-of-other-objects
json - Java+Jackson : How to serialize a object containing array/list of other objects - Stack Overflow
I can't use QueryBuilder's of elastic's java API directly. Moreover, that different project is way out my or our team's scope. 2017-02-07T10:40:21.47Z+00:00 ... My workaround to proceed for now. Modified DeleteQuery and DeleteQuerySerializer as below: class DeleteQuery { List<String> mustParams; } class DeleteQuerySerializer extends StdSerializer<DeleteQuery> { protected DeleteQuerySerializer(Class<DeleteQuery> t) { super(t); } public DeleteQuerySerializer() { this(null); } @Override public void serialize(DeleteQuery value, JsonGenerator jsonGen, SerializerProvider provider) throws IOException { jsonGen.writeStartObject(); jsonGen.writeObjectFieldStart("query"); jsonGen.writeObjectFieldStart("bool"); String mustParam = String.join(",", value.mustParams); jsonGen.writeFieldName("must"); jsonGen.writeRawValue("[" + mustParam + "]"); jsonGen.writeEndObject(); } }
🌐
Stack Overflow
stackoverflow.com › questions › 65637249 › how-do-i-serialize-a-list-of-objects-with-jackson
java - How do I serialize a list of objects with Jackson? - Stack Overflow
January 8, 2021 - Class B has a member variable private List<A> as; and some other members with Double as the data type. What do I have to do to serialize/desirialize an object of class B? I know there is an annotation @JsonSerialize(using = CustomSerializer.class) but I think it doesn't work with lists.
🌐
LogicBig
logicbig.com › tutorials › misc › jackson › json-format-collection-and-number-as-object.html
Jackson JSON - Using @JsonFormat to serialize Collection And Number As JSON Objects
August 11, 2020 - public class ExampleMain { public static void main(String[] args) throws IOException { Employee employee = new Employee(); employee.setName("Amy"); employee.setDept("Admin"); ArrayListEx<String> list = new ArrayListEx<>(); list.add("111-111-111"); list.add("222-222-222"); employee.setPhoneNumbers(list); employee.setSalary(new BigIntegerEx("4000")); System.out.println("-- before serialization --"); System.out.println(employee); System.out.println("-- after serialization --"); ObjectMapper om = new ObjectMapper(); String jsonString = om.writeValueAsString(employee); System.out.println(jsonString); } }
🌐
Stack Abuse
stackabuse.com › definitive-guide-to-jackson-objectmapper-serialize-and-deserialize-java-objects
Definitive Guide to Jackson ObjectMapper - Serialize and Deserialize Java Objects
October 27, 2023 - Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations. It's one of the most widely used libraries for this task, and runs under the hood of many other frameworks.
🌐
Baeldung
baeldung.com › home › json › jackson › intro to the jackson objectmapper
Intro to the Jackson ObjectMapper | Baeldung
December 9, 2025 - Always use the latest versions from the Maven central repository for jackson-databind. Let’s start with the basic read and write operations. The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.
🌐
YouTube
youtube.com › watch
Java json 01 create an arraylist to serialize with Jackson library - YouTube
Shows how to prepare an arraylist of a class. Preparing for use of a json library called Jackson. Part 1 of 3 for how to read and write json files using java
Published: January 29, 2019
🌐
CodeMiner42
blog.codeminer42.com › home › posts › serialization and deserialization in java using jackson
Serialization and Deserialization in Java using Jackson - The Miners
May 29, 2023 - By default when we serialize an object, Jackson will map JSON keys matching the name of the object’s attributes. To change this behavior we use @JsonProperty on the fields. We will pass a string value to the annotation to specify which name should be mapped to JSON. ... public class Person { @JsonProperty("fullname") private String name; private int height; private int weight; @JsonProperty("vehicles") private List<Car> cars = new ArrayList<Car>(); .