Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson 2.* and json to ArrayList<>

Tags:

java

json

jackson

I'm trying to deserialize a Json array to an ArrayList of objects. I have found some documentation on what i'm trying to do, but I'm getting an error on compile.

Here is how I'm trying to approach it with Jackson 2.2.2:

ArrayList<Friends> list =  objectMapper.readValue(result, new TypeReference<ArrayList<Friends>>() {});

The error I get is:

The method readValue(String, Class<T>) in the type ObjectMapper is not applicable for the arguments (String, new TypeReference<ArrayList<Friends>>(){})

I'm guessing some of the references I have been reading is based on an older version of Jackson. How can this be accomplished in Jackson 2.2 +

like image 275
Michael Avatar asked Feb 15 '23 20:02

Michael


1 Answers

Try the following:

JavaType type = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Friends.class);
ArrayList<Friends> friendsList = objectMapper.readValue(result, type);

Note that I pulled this from the following answer: Jackson and generic type reference

As of Jackson 1.3 (a while back) they recommend you use TypeFactory.

EDIT
On further inspection, what you have above is working for me... I'm able to pass in a TypeReference sub class to readValue and everything works correctly. Are you sure you have the right type of TypeReference imported? Usually those types of errors are from accidentally importing the wrong type (some other library might have a TypeReference class).

like image 64
Polaris878 Avatar answered Feb 17 '23 11:02

Polaris878