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 - 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 - How to de/serialize List<Object> with Jackson? - Stack Overflow
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
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
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 - Custom Serialize List of Objects in Jackson - Stack Overflow
Which works for the first Day object ... Day object. This is confusing since I do hand in the List. Am I missing something simple? Do I need to handle this inside the serializer somehow? ... Do you mean that serialization only includes the first value? That should not be the case: List (or array) should be handled by Jackson just fine, calling custom serializer for each element, separately. But one thing you should try for troubleshooting is to see what happens when List is a property of a POJO: there ... More on stackoverflow.com
🌐 stackoverflow.com
March 29, 2018
🌐
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.
🌐
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"}]
🌐
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.
🌐
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.
🌐
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.
Find elsewhere
🌐
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 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
🌐
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 - 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/
🌐
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
March 5, 2015 - As we can see elements of the MyItem objects list have been properly serialized as JSON string, with all properties with the right value. What is missing however is the information, for each object, about his real type, that is, of which of different concrete subclasses it is an instance. Without this information, deserialization of the JSON representation in a list of objects of concrete subclasses is not possible, because Jackson may not know the actual objects type.
🌐
Stack Overflow
stackoverflow.com › questions › 49543964 › custom-serialize-list-of-objects-in-jackson
java - Custom Serialize List of Objects in Jackson - Stack Overflow
March 29, 2018 - final DaySerializer daySerializer = new DaySerializer(Day.class); final ObjectMapper mapper = new ObjectMapper(); final SimpleModule module = new SimpleModule("DaySerializer", new Version(2, 1, 3, null, null, null)); module.addSerializer(Day.class, daySerializer); mapper.registerModule(module); try { mapper.writerWithDefaultPrettyPrinter().writeValue(new File(this.jsonPath + "/Days.json"), days); } catch (final Exception e) { e.printStackTrace(); } ... @Override public void serialize(final Day day, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOExcepti
🌐
Stack Overflow
stackoverflow.com › questions › 34815620 › serializing-lists-of-objects-with-jackson-deep-and-or-shallow
java - Serializing Lists of Objects with Jackson: "deep" and/or "shallow" - Stack Overflow
January 15, 2016 - When serializing Lists of Objects with Jackson I would like to control whether the Object is serialized “deep” or “shallow”. For Example: Test has two lists of class X objects public class Test {...
🌐
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>(); .
🌐
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 ...
🌐
Stack Overflow
stackoverflow.com › a › 17612401
java - JSON Jackson serialize deserialize List of List - Stack Overflow
I use Json-Jackson to serialize/deserialize my object and all goes well with built-in classes. String, int, and so on are very good. But now I must serialize/deserialize an object built in a particular manner. Follow the declaration: class A implements Serializable { private String id; private List<B> bobjs; ...getters & setters (but not for String id) } class B implements Serializable { private String id; private String label; private List<C> cobjs; ...getters & setters (but not for String id) } class C implements Serializable { private String id; private String label; private BigDecimal counts; ...getters & setters (but not for String id) }
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – unmarshall to collection/array
Jackson - Unmarshall to Collection/Array | Baeldung
April 26, 2024 - @Test public void givenJsonArray_whenDeserializingAsListWithJavaTypeHelp_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); CollectionType javaType = mapper.getTypeFactory() .constructCollectionType(List.class, MyDto.class); List<MyDto> asList = mapper.readValue(jsonArray, javaType); assertThat(asList.get(0), instanceOf(MyDto.class)); } One final note is that the MyDto clas