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
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.

🌐
Medium
cowtowncoder.medium.com › jackson-tips-custom-list-serialization-4566f734c58d
Jackson Tips: custom List serialization | by @cowtowncoder | Medium
May 31, 2021 - 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 ...
Discussions

How to de/serialize List<Object> with Jackson?
Yes, thanks. Since the object list resides in some other classes, I'd add mixins to use the custom de/serializer. More on stackoverflow.com
🌐 stackoverflow.com
java - Jackson's ObjectMapper, serialize list - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
February 18, 2025
json - Java+Jackson : How to serialize a object containing array/list of other objects - Stack Overflow
I am trying to generate following ... version, list of content Ids) { "query": { "bool": { "must": [ { "term": { "version": { "value": "published" } } }, { "terms": { "contentId": [ "contentId-123", "contentId-456" ] } } ] } } } The above json is a query body for elastic-search delete request. version and contentId mentioned in above json are actual fields/attributes of content object or data model. I am getting this exception while serializing the object: com.fasterxml.jackson.core.Json... More on stackoverflow.com
🌐 stackoverflow.com
Serializing list does not include type annotations
This may be related to #292, since you mentioned it may also have been related to Collections. However, since I can't find the 2.2.4 snapshot for download to test on it or this new problem, I t... More on github.com
🌐 github.com
9
September 6, 2013
🌐
Studytrails
studytrails.com › 2016 › 09 › 12 › java-jackson-serialization-list
Java json – jackson List serialization – Studytrails
(); Lion lion = new Lion("Samba"); Elephant elephant = new Elephant("Manny"); animals.add(lion); animals.add(elephant); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(System.out, animals); } } ... No type info! To add type info while serializing Lists directly you need to configure the mapper in this way · mapper.writerWithType(new TypeReference&ltList &ltAnimal&gt&gt() { }).writeValue(System.out, animals); ... [{"@class":"com.studytrails.json.jackson.Lion","name":"Samba"}, {"@class":"com.studytrails.json.jackson.Elephant","name":"Manny"}]
🌐
Oracle
blogs.oracle.com › javamagazine › java-json-serialization-jackson
Looking for a fast, efficient way to serialize and share Java objects? Try Jackson.
Jackson can be used to automatically serialize this class to JSON so that it can, for example, be sent over the network to another service that may or may not be implemented in Java and that can receive JSON-formatted data.
🌐
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.
🌐
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.
🌐
Baeldung
baeldung.com › home › json › jackson › intro to the jackson objectmapper
Intro to the Jackson ObjectMapper | Baeldung
December 9, 2025 - How to use the @JsonView annotation in Jackson to perfectly control the serialization of your objects (without and with Spring).
🌐
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); } }
Find elsewhere
🌐
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)
May 8, 2025 - 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.
🌐
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
class SearchParam { boolean isMultivalued; String fieldName; String value; List<String> values; @Override public String toString() { final StringBuilder sb = new StringBuilder("SearchParam{"); sb.append("isMultivalued=").append(isMultivalued); sb.append(", fieldName='").append(fieldName).append('\''); sb.append(", value='").append(value).append('\''); sb.append(", values=").append(values); sb.append('}'); return sb.toString(); } } class DeleteQuery { List<SearchParam> mustParams; } class DeleteQuerySerializer extends StdSerializer<DeleteQuery> { protected DeleteQuerySerializer(Class<DeleteQuer
🌐
Google Groups
groups.google.com › g › jackson-user › c › oOtEBhoDIgo › m › 8rTqBUgaCwAJ
List with one element
By default, Jackson serializes Lists as Lists. It does not unwrap single element. It is possible to change this behavior by enabling SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED (or using `@JsonFormat` per-property annotation with similar setting) so I would try to figure out ...
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – unmarshall to collection/array
Jackson - Unmarshall to Collection/Array | Baeldung
April 26, 2024 - All Courses are 30% off until 31st March, 2026 ... This tutorial will show how to deserialize a JSON Array to a Java Array or Collection with Jackson 2. If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial. ... @Test public void givenJsonArray_whenDeserializingAsArray_thenCorrect() 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); // [{"stringValue":"a","intValue":1,"booleanValue":true}, // {"stringValue":"bc","intValue":3,"booleanValue":false}] MyDto[] asArray = mapper.readValue(jsonArray, MyDto[].class); assertThat(asArray[0], instanceOf(MyDto.class)); }
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 303
Serializing list does not include type annotations · Issue #303 · FasterXML/jackson-databind
September 6, 2013 - 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof DataValue)) return false; DataValue other = (DataValue) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(JacksonList.class.getName()); module.setMixInAnnotation(JacksonList.DataValue.class, Mixins.class);
Author   daw3rd
🌐
Apache
pekko.apache.org › docs › pekko › current › serialization-jackson.html
Serialization with Jackson · Apache Pekko Documentation
April 23, 2024 - copysourcefinal case class Zoo(primaryAttraction: Animal) extends MySerializable @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes( Array( new JsonSubTypes.Type(value = classOf[Lion], name = "lion"), new JsonSubTypes.Type(value = classOf[Elephant], name = "elephant"), new JsonSubTypes.Type(value = classOf[Unicorn], name = "unicorn"))) sealed trait Animal final case class Lion(name: String) extends Animal final case class Elephant(name: String, age: Int) extends Animal @JsonDeserialize(`using` = classOf[UnicornDeserializer]) sealed trait Unicorn extends Animal @JsonType
🌐
Davismol
davismol.net › 2015 › 03 › 05 › jackson-json-deserialize-a-list-of-objects-of-subclasses-of-an-abstract-class
Jackson JSON: deserialize a list of objects of subclasses of an abstract class | Dede Blog
February 14, 2024 - In this post we see how to serialize and deserialize in JSON a Java class that declares an instance variable consisting in a list of objects of an abstract class that contains objects of its various concrete subclasses.
Top answer
1 of 1
14

Just

new ObjectMapper().writeValueAsString(myResult);

The type of the list won't be lost due to type erasure in the same way it would be in the first example.


Note that for vanilla serialization of a list or generic list, it's not necessary to specify the list component types, as demonstrated in the example in the original question. All three of the following example serializations represent the List<Bar> with the exact same JSON.

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Baz baz = new Baz("BAZ", 42);
    Zab zab = new Zab("ZAB", true);
    List<Bar> bars = new ArrayList<Bar>();
    bars.add(baz);
    bars.add(zab);

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

    String json1 = mapper.writeValueAsString(bars);
    System.out.println(json1);
    // output:
    // [{"name":"BAZ","size":42},{"name":"ZAB","hungry":true}]

    Foo foo = new Foo(bars);

    String json2 = mapper.writeValueAsString(foo);
    System.out.println(json2);
    // output:
    // {"bars":[{"name":"BAZ","size":42},{"name":"ZAB","hungry":true}]}

    mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
    ObjectWriter typedWriter = mapper.writerWithType(mapper.getTypeFactory().constructCollectionType(List.class, Bar.class));

    String json3 = typedWriter.writeValueAsString(bars);
    System.out.println(json3);
    // output:
    // [{"name":"BAZ","size":42},{"name":"ZAB","hungry":true}]
  }
}

class Foo
{
  List<Bar> bars;
  Foo(List<Bar> b) {bars = b;}
}

abstract class Bar
{
  String name;
  Bar(String n) {name = n;}
}

class Baz extends Bar
{
  int size;
  Baz(String n, int s) {super(n); size = s;}
}

class Zab extends Bar
{
  boolean hungry;
  Zab(String n, boolean h) {super(n); hungry = h;}
}

A typed writer is useful when serializing with additional type information. Note how the json1 and json3 outputs below differ.

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectMapper.DefaultTyping;
import org.codehaus.jackson.map.ObjectWriter;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Baz baz = new Baz("BAZ", 42);
    Zab zab = new Zab("ZAB", true);
    List<Bar> bars = new ArrayList<Bar>();
    bars.add(baz);
    bars.add(zab);

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
    mapper.enableDefaultTypingAsProperty(DefaultTyping.OBJECT_AND_NON_CONCRETE, "type");

    String json1 = mapper.writeValueAsString(bars);
    System.out.println(json1);
    // output:
    // [
    //   {"type":"com.stackoverflow.q8416904.Baz","name":"BAZ","size":42},
    //   {"type":"com.stackoverflow.q8416904.Zab","name":"ZAB","hungry":true}
    // ]

    Foo foo = new Foo(bars);

    String json2 = mapper.writeValueAsString(foo);
    System.out.println(json2);
    // output:
    // {
    //   "bars":
    //   [
    //     "java.util.ArrayList",
    //     [
    //       {"type":"com.stackoverflow.q8416904.Baz","name":"BAZ","size":42},
    //       {"type":"com.stackoverflow.q8416904.Zab","name":"ZAB","hungry":true}
    //     ]
    //   ]
    // }

    mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
    mapper.enableDefaultTypingAsProperty(DefaultTyping.OBJECT_AND_NON_CONCRETE, "type");
    ObjectWriter typedWriter = mapper.writerWithType(mapper.getTypeFactory().constructCollectionType(List.class, Bar.class));

    String json3 = typedWriter.writeValueAsString(bars);
    System.out.println(json3);
    // output:
    // [
    //   "java.util.ArrayList",
    //   [
    //     {"type":"com.stackoverflow.q8416904.Baz","name":"BAZ","size":42},
    //     {"type":"com.stackoverflow.q8416904.Zab","name":"ZAB","hungry":true}
    //   ]
    // ]
  }
}
🌐
GitHub
github.com › FasterXML › jackson-databind › wiki › Serialization-features
Serialization features · FasterXML/jackson-databind Wiki · GitHub
Jackson defines a set of features that relate to serialization (writing Java objects as JSON), and that can be changed on per-call basis (by using ObjectWriter).
Author   FasterXML