Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jackson to deserialise an array of objects

Tags:

java

json

jackson

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" }  //Java 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" }]  //Java List<MyClass> entries = ? 

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

like image 327
Ollie Edwards Avatar asked Jun 14 '11 20:06

Ollie Edwards


People also ask

How do you deserialize an array of objects in Java?

We can easily deserialize JSON Array into Java Array by using the readValue() method of the ObectMapper class. In the readValue() method, we pass two parameters, i.e., jsonString and Student[].

What is Jackson deserialization?

Deserialization annotations are used when we deserialize JSON string into an Object. Jackson library provides several deserialization annotations such as @JsonCreator, @JacksonInject, @JsonAnySetter, etc. These annotations are mostly used in setter.

How does Jackson deserialize dates from JSON?

This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);


2 Answers

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)); 
like image 83
Programmer Bruce Avatar answered Sep 28 '22 04:09

Programmer Bruce


From Eugene Tskhovrebov

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

This solution seems to be the best for me.

like image 30
Marthym Avatar answered Sep 28 '22 03:09

Marthym