4

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 +

Michael
  • 1,241
  • 1
  • 13
  • 25

1 Answers1

8

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

Community
  • 1
  • 1
DigitalZebra
  • 39,494
  • 39
  • 114
  • 146
  • Awesome. Exactly what was needed I just couldn't get the construction collection type right. Thanks Polaris! – Michael Oct 29 '13 at 21:48