2

I want to use Jackson to parse a list of objects. With Gson, I can do this easily:

List<MyType> list = new Gson().fromJson(input, Types.listOf(MyType.class));

With Jackson, it seems to be more difficult:

List<MyType> list = new ObjectMapper().readValue(input, /* What to put here? */);

The code needs to work for lists of any type (like Gson does), so I can't just make a type that contains a list of MyType and pass that in.

I've tried using new TypeLiteral<List<MyType>>(){}, which works, but only for a single type. If I pass in the type to the method, it doesn't work any more:

public <T> List<T> parse(Class<T> myType) {
    // returns a List<Map<?,?>> instead of List<T>
    return new ObjectMapper().readValue(input, new TypeLiteral<List<T>>(){});
}

How do I do this with Jackson?

3 Answers 3

3

It is more easy

MyType myType = new ObjectMapper().readValue(input, new TypeReference<List<MyType>>() {});

updated answer.

Sign up to request clarification or add additional context in comments.

1 Comment

No, the input contains a list of MyType, not a single object.
2

The following works with Jackson 2.7 and higher. It doesn't use the deprecated static methods to get the TypeFactory. Instead, it gets the TypeFactory from the object mapper.

final ObjectMapper mapper = new ObjectMapper();

mapper.readValue(input, mapper.getTypeFactory().constructCollectionType(List.class, MyType.class));

Comments

2

I've found the solution in the mean time. Apparently, Jackson provides its own way of working around this:

List<MyType> list = new ObjectMapper().readValue(input, CollectionType.construct(List.class, SimpleType.construct(MyType.class));

2 Comments

Both construct() methods are deprecated since Jackson 2.7.
Gee, a 9 year old answer is out of date? Who would've guessed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.