Michael
Michael

Reputation: 1251

Jackson 2.* and json to ArrayList<>

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 +

Upvotes: 4

Views: 3961

Answers (1)

DigitalZebra
DigitalZebra

Reputation: 41503

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).

Upvotes: 8

Related Questions