snippetjavaCritical
How to use Jackson to deserialise an array of objects
Viewed 0 times
arrayhowjacksonuseobjectsdeserialise
Problem
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:
Now for an array I want to do this:
Anyone know if there is a magic missing command? If not then what is the solution?
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 entries = ?Anyone know if there is a magic missing command? If not then what is the solution?
Solution
First create a mapper :
As Array:
As List:
Another way to specify the List type:
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 myObjects = mapper.readValue(jsonInput, new TypeReference>(){});Another way to specify the List type:
List myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));Code Snippets
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();MyClass[] myObjects = mapper.readValue(json, MyClass[].class);List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));Context
Stack Overflow Q#6349421, score: 2365
Revisions (0)
No revisions yet.