Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue when trying to use Jackson in java

Tags:

java

jackson

I'm trying to use Jackson to convert some JSON data into Java objects ,a list of objects to be precise,but I get this error:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of entitylayer.Detail out of START_ARRAY token

this is the code:

 ObjectMapper mapper = new ObjectMapper(); 
 List<Detail> lcd = (List<Detail>) mapper.readValue(ld, Detail.class);

ld is the list in Json format, this is the part that makes me comfused in the jackson tutorial. what does new File("user.json") represent? I assumed that was the string in json format I wanted to convert, that's why I used ld.

I hope you can help me out with it

like image 890
eddy Avatar asked Dec 08 '10 21:12

eddy


People also ask

How do I ignore unrecognized field Jackson?

You can ignore the unrecognized fields by configuring the ObjectMapper class: mapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false);

How does Jackson work Java?

The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON. The Jackson ObjectMapper can also create JSON from Java objects.

Does Jackson use the default constructor?

By default, Java provides a default constructor(if there's no parameterized constructor) which is used by Jackson to parse the response into POJO or bean classes. and the exception log.


1 Answers

From the tutorial you linked (other Collections work the same way):

So if you want to bind data into a Map you will need to use:

Map<String,User> result = mapper.readValue(src, new TypeReference<Map<String,User>>() { });

where TypeReference is only needed to pass generic type definition (via anynomous inner class in this case): the important part is > which defines type to bind to.

If you don't do this (and just pass Map.class), call is equivalent to binding to Map (i.e. "untyped" Map), as explained above.

Edit:

If you insist on being spoon fed:

List<Detail> lcd = mapper.readValue(ld, new TypeReference<List<Detail>>() {});
like image 200
OrangeDog Avatar answered Sep 30 '22 03:09

OrangeDog