0

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.

John
  • 1,375
  • 4
  • 17
  • 40
  • Have you already read a simple tutorial like this https://www.baeldung.com/jackson-object-mapper-tutorial ? If so, what is your actual error? Or your actual question? Because `Json` doesn't exist in Jackson (as far as I know) – Tom Mar 01 '19 at 14:28
  • I can't get class from a generic class. For example, if I do Test.class it is ok, but I can't get class like this Test.class // not working. – John Mar 01 '19 at 14:31
  • 2
    @Oleg, could you show your example `JSON` payload and `Test` class? `sss` is invalid `JSON` – Michał Ziober Mar 01 '19 at 14:41

1 Answers1

1

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:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    @Oleg, no problem. I'm glad I could help. You can also change title to `How to decode geeneric data in Jackson?`. Generic in this question is a key word. – Michał Ziober Mar 01 '19 at 14:51