You can deserialize directly to a list by using the TypeReference wrapper. An example method:

public static <T> T fromJSON(final TypeReference<T> type,
      final String jsonPacket) {
   T data = null;

   try {
      data = new ObjectMapper().readValue(jsonPacket, type);
   } catch (Exception e) {
      // Handle the problem
   }
   return data;
}

And is used thus:

final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);

TypeReference Javadoc

Answer from Perception on Stack Overflow
🌐
Baeldung
baeldung.com › home › json › jackson › jackson – unmarshall to collection/array
Jackson - Unmarshall to Collection/Array | Baeldung
April 26, 2024 - Jackson can easily deserialize to a Java Array: @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.
Discussions

jackson should provides a method which can deserialize a collection that contains different type items
There was an error while loading. Please reload this page More on github.com
🌐 github.com
8
September 6, 2022
java - Jackson Json deserialization of an object to a list - Stack Overflow
I'm consuming a web service using Spring's RestTemplate and deserializing with Jackson. In my JSON response from the server, one of the fields can be either an object or a list. meaning it can be ... More on stackoverflow.com
🌐 stackoverflow.com
April 28, 2025
java - Deserialize list of objects with inner list with Jackson - Stack Overflow
I have such an entity: public class User { private Long id; private String email; private String password; private List roles; //set of constructors, getters, set... More on stackoverflow.com
🌐 stackoverflow.com
August 1, 2016
apex - How to deserialize JSON array into list of objects - Salesforce Stack Exchange
Looks like the payload got serialized twice somehow. Ideally you would fix that so it is serialized just once instead. However, you can fix it in the interim by deserializing first into a String, then into your List. More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
March 4, 2022
🌐
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 - The result obtained in this case is as follows, where we can see that in the JSON string for each item in the list of MyItem, a new property called “type” (specified by the annotation attribute property = “type”) has been added and it has been fill with the full name of the concrete subclass the object was an instance of (specified by the annotation attribute use = Id.CLASS). In this way, during deserialization we have the information about the concrete class to be used to instantiate each element.
🌐
Programming-books
programming-books.io › essential › java › deserialize-json-collection-to-collection-of-objects-using-jackson-e8851ae7f384497fa3e03815dda80163
Deserialize JSON collection to collection of Objects using Jackson
TypeReference<Person> mapType = new TypeReference<Map<String, Person>>() {}; Map<String, Person> list = mapper.readValue(jsonString, mapType); ... import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; ... Failing to do so may lead to loss of generic type argument which will lead to deserialization failure.
🌐
W3Docs
w3docs.com › java
How to use Jackson to deserialise an array of objects
The readValue() method takes the ... array of objects of the specified class. You can also use the readValue() method to deserialize a JSON array into a List of objects, like this:...
🌐
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 - We can use the ObjectMapper.readValue() method for converting a JSON text to collection object. The following example demonstrates how to convert the JSON text to List. package net.javaguides.jackson; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JacksonJsonToList { @SuppressWarnings("unchecked") public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { // Create ObjectMapper object.
🌐
Javatpoint
javatpoint.com › deserialize-to-collection-and-array-in-jackson
Deserialize to Collection/Array in Jackson - javatpoint
Deserialize to Collection/Array in Jackson with Jackson Tutorial, Setup Environment, First Application Jackson, ObjectMapper Class, Object Serialization using Jackson, Data Binding, Tree Model etc.
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3592
jackson should provides a method which can deserialize a collection that contains different type items · Issue #3592 · FasterXML/jackson-databind
September 6, 2022 - jackson should provides a method which can deserialize a collection that contains different type items#3592 ... Is your feature request related to a problem? Please describe. String collectionJson = "[ {\"school" : \"xxx\", ... }, {\"student" : \"yyy\", ...} ]"; List<JavaType> javaTypeList = new ArrayList<>(); javaTypeList.add(schoolJavaType); javaTypeList.add(studentJavaType); // like fastjson#parseArray(collectionJsonString, arrayOfJavaLangReflectType); List<Object> objectList = objectMapper.parseListByType(collectionJson, javaTypeList);
Author   zrlw
Find elsewhere
Top answer
1 of 2
8

Since you are using Jackson I think what you need is JsonDeserializer class (javadoc).

You can implement it like this:

public class ListOrObjectGenericJsonDeserializer<T> extends JsonDeserializer<List<T>> {

    private final Class<T> cls;

    public ListOrObjectGenericJsonDeserializer() {
        final ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        this.cls = (Class<T>) type.getActualTypeArguments()[0];
    }

    @Override
    public List<T> deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
        final ObjectCodec objectCodec = p.getCodec();
        final JsonNode listOrObjectNode = objectCodec.readTree(p);
        final List<T> result = new ArrayList<T>();
        if (listOrObjectNode.isArray()) {
            for (JsonNode node : listOrObjectNode) {
                result.add(objectCodec.treeToValue(node, cls));
            }
        } else {
            result.add(objectCodec.treeToValue(listOrObjectNode, cls));
        }
        return result;
    }
}

...

public class ListOrObjectResultItemJsonDeserializer extends ListOrObjectGenericJsonDeserializer<ResultItem> {}

Next you need to annotate your POJO field. Let's say you have classes like Result and ResultItem:

public class Result {

    // here you add your custom deserializer so jackson will be able to use it
    @JsonDeserialize(using = ListOrObjectResultItemJsonDeserializer.class)
    private List<ResultItem> result;

    public void setResult(final List<ResultItem> result) {
    this.result = result;
    }

    public List<ResultItem> getResult() {
        return result;
    }
}

...

public class ResultItem {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(final String value) {
        this.value = value;
    }
}

Now you can check your deserializer:

// list of values
final String json1 = "{\"result\": [{\"value\": \"test\"}]}";
final Result result1 = new ObjectMapper().readValue(json1, Result.class);
// one value
final String json2 = "{\"result\": {\"value\": \"test\"}}";
final Result result2 = new ObjectMapper().readValue(json2, Result.class); 

result1 and result2 contain the same value.

2 of 2
6

You can achieve what you want with a configuration flag in Jackson's ObjectMapper:

ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
    .featuresToEnable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
    .build();

Just set this ObjectMapper instance to your RestTemplate as explained in this answer, and in the class you are deserializing to, always use a collection, i.e. a List:

public class Response {

    private List<Result> result;

    // getter and setter
}
Top answer
1 of 1
4

If you have access to Role class you can just add such constructor:

private Role(String role) {
   this.role = role;
}

or static factory methods:

@JsonCreator
public static Role fromJson(String value){
    Role role = new Role();
    role.setRole(value);
    return role;
}

@JsonValue
public String toJson() {
    return role;
}

Otherwise you will have to write custom deserealizer and register it on object mapper like this:

public static class RoleSerializer extends JsonSerializer {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString(((Role) value).getRole());
    }
}

public static class RoleDeserializer extends JsonDeserializer {
    @Override
    public Role deserialize(JsonParser jsonParser,DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        Role role =  new Role();
        role.setRole(node.asText());
        return role;
    }
}

Here is demo: https://gist.github.com/varren/84ce830d07932b6a9c18

FROM: [{"email": "user@email","roles": ["REGISTERED_USER"]}]

TO OBJ: [User{id=null, email='user@email', password='null', roles=Role{role='REGISTERED_USER'}}]

TO JSON:[{"email":"user@email","roles":["REGISTERED_USER"]}]

Ps: If you use ObjectMapper like this

Arrays.asList(objectMapper.readValue(multipartFile.getBytes(), User[].class));

then code from demo will work, but you will probably have to set custom Bean in Spring for jackson ObjectMapper to make RoleDeserializer and RoleSerializer work everywhere. Here is more info: Spring, Jackson and Customization (e.g. CustomDeserializer)

🌐
Reddit
reddit.com › r/dotnet › trying to deserialize a json into a list of objects so that they can be passed on to a view.
r/dotnet on Reddit: Trying to Deserialize a JSON into a list of Objects so that they can be passed on to a view.
July 29, 2022 -

Let me prefix this by saying I am very new to all this so any help would be so very appreciated - i've been trying to crack this all day and it's been a real struggle. Im making this webapp in ASP.NET core btw. So I've managed to call the twitter api and return back some tweets as JSON depending on a search query. I am then trying to deserialize these into C# objects (using the Tweet class). I then want to pass these objects through as a list to the view for it to render them all out But I just can't seem to get it to work.

I am trying to put desrialize the JSON that comes back into Tweet objects and put them into a ViewModel and then pass the viewmodel to the view. This is what comes back from the API call so I know thats working ok. This is what the Tweet class looks like. The SocialMediaType property is a class in itself, and just has two properties on it which are an Id and name which are given default values as they will always be the same. The error page
🌐
Studytrails
studytrails.com › 2016 › 09 › 12 › java-jackson-serialization-list
Java json – jackson List serialization – Studytrails
We will have to serialize the zoo from its current location and deserialize it at the target location. (a teleportation machine) 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; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class SerializeZoo { public static void main(String[]
🌐
Mosy
thepracticaldeveloper.com › java-and-json-jackson-serialization-with-objectmapper
Java and JSON – Jackson Serialization with ObjectMapper | Mosy
July 31, 2018 - @Test public void deserializePersonV2AsMap() throws IOException { var mapper = new ObjectMapper(); var json = "{\"name\":\"Juan Garcia\",\"birthdate\":[1980,9,15]," + "\"hobbies\":[\"football\",\"squash\"]}"; Map value = mapper.readValue(json, Map.class); log.info("Deserializing a JSON object as a map: {}", value); assertThat(value.get("name")).isEqualTo("Juan Garcia"); assertThat(value.get("birthdate")) .isEqualTo(Lists.newArrayList(1980, 9, 15)); assertThat(value.get("hobbies")) .isEqualTo(Lists.newArrayList("football", "squash")); } Sometimes, it might be convenient to deserialize Java obje
🌐
GitHub
gist.github.com › tyb › 2fc1d7b064b508e10cc7e7fe505fd516
json object deserialization/unmarshalling to java object(mainly array/list) with Jackson · GitHub
json object deserialization/unmarshalling to java object(mainly array/list) with Jackson - jackson_templates.java
🌐
Medium
medium.com › @jamokoy397 › jackson-magic-deserializing-non-existent-lists-into-empty-lists-java-objectmapper-300ede79fa04
Jackson Magic: Deserializing Non-Existent Lists into Empty Lists (Java, ObjectMapper) | by Jamokoy Lancey | Medium
October 21, 2024 - In this example, we create a User object, serialize it to JSON using the writeValueAsString() method, and then deserialize it back to a User object using the readValue() method. This demonstrates the basic workflow of Jackson in handling ...
🌐
Google Groups
groups.google.com › g › jackson-user › c › EbltfyXSVV8
How to deserialize a JSON array to a singly linked list by using Jackson
June 17, 2015 - @Tatu You’re right, after I make the SinglyLinkedListNode implement java.util.List, Jackson can automatically deserialize a JSON array into a singly linked list. The code of SinglyLinkedListNode is as the following:
🌐
Stack Overflow
stackoverflow.com › questions › 56418361 › deserialize-json-with-list-of-nested-objects › 56422254
java - Deserialize json with list of nested objects - Stack Overflow
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.util.List; public class JsonApp { public static void main(String[] args) throws Exception { File jsonFile = new File("./resource/test.json").getAbsoluteFile(); ObjectMapper mapper = new ObjectMapper(); Root root = mapper.readValue(jsonFile, Root.class); System.out.println(root); } } class Root { private Class1 class1; //getters, setters, toString } class Class1 { private String prop1; private List<NestedProps> prop2; //getters, setters, toString } class NestedProps { private List<NestedProp> nestedProp; //getters, setters, toString } class NestedProp { private String p1; private String p2; //getters, setters, toString }
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3257
How to write a Deserializer which only works for List<String>, but not for other Lists? · Issue #3257 · FasterXML/jackson-databind
August 24, 2021 - I want to write a Deserializer which removes blank strings from arrays. I am not sure why, but my Deserializer is never called. (I don't see the Hello World in the console). Additionally, the array with the blank string is written to the database with the blank strings. So, Jackson just skips my Deserializer for any reason.
Author   Alwinator