John
John

Reputation: 1601

How to decode generic data in Jackson?

How can I do like this:

Test<String> data = OBJECT_MAPPER.decodeValue("sss", Test<String>.class);

When I call this operation I get an error. I need decode generic class.

Thanks for the help.

Upvotes: 0

Views: 462

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38655

You can use TypeReference. Test<String>.class is not possible in Java.

TypeReference testStringType = new TypeReference<Test<String>>() { };
Object value = mapper.readValue(json, testStringType);

Also works:

JavaType javaType = mapper.getTypeFactory().constructParametricType(Test.class, String.class);
Test<String> value1 = mapper.readValue(json, javaType);

See also:

Upvotes: 1

Related Questions