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
You can ignore the unrecognized fields by configuring the ObjectMapper class: mapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false);
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.
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.
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.
If you insist on being spoon fed:
List<Detail> lcd = mapper.readValue(ld, new TypeReference<List<Detail>>() {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With