How to decode generic data in Jackson?

有些话、适合烂在心里 提交于 2021-01-29 05:42:00

问题


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.


回答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:

  • Jackson - Deserialize using generic class
  • Jackson - Deserialize Generic class variable


来源:https://stackoverflow.com/questions/54946568/how-to-decode-generic-data-in-jackson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!