How to use Jackson to deserialise an array of objects

2021-6-3 anglehua

The Jackson data binding documentation indicates that Jackson supports deserialising "Arrays of all supported types" but I can't figure out the exact syntax for this.

For a single object I would do this:

//json input
    "id" : "junk",
    "stuff" : "things"

MyClass instance = objectMapper.readValue(json, MyClass.class);

Now for an array I want to do this:

//json input
    "id" : "junk",
    "stuff" : "things"
    "id" : "spam",
    "stuff" : "eggs"

List<MyClass> entries = ?

Anyone know if there is a magic missing command? If not then what is the solution?

First create a mapper :

import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();

As Array:

MyClass[] myObjects = mapper.readValue(json, MyClass[].class);

As List:

List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});

Another way to specify the List type:

List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));

From Eugene Tskhovrebov

List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))

This solution seems to be the best for me.


Powered by emlog 京ICP备15036472号-3 sitemap