Question

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

Was it helpful?

Solution

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>>() {});

OTHER TIPS

As an alternative strategy, dealing with arrays is slightly more convenient, because you can easily specify type. So alternatively you could also do this:

Detail[] details = mapper.readValue(ld, Detail[].class);

Arrays are often underused, at least when dealing with Jackson. As long as you don't have to modify results too much they are very convenient to use, since types are nicely contained without needing to use generics (and as result, type-safety is strong; it's not just compiler fluff).

Alternatively parse the JSON yourself and create whatever POJOs you wish to create. I did that to transform JSON to JAXB.

Refer to the "Streaming API Example" section at http://wiki.fasterxml.com/JacksonInFiveMinutes

Its easier than you would expect it to be.

Whenever you get this error, first check if the JSON string you are trying to convert to is a proper JSON string. If you try to create your own JSON string for local testing your code then you end up in getting this error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top