Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

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?

1 Answer

0 votes
by (46k points)

You need to create a mapper first:

import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3

ObjectMapper mapper = new ObjectMapper();

 

To specify as List use:

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

or

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

 

To specify as Array use:

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...