Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Generic type for the Jackson ObjectMapper

Java erases normally the Generics data on compilation, but there is a possibility to get that information (the Jackson ObjectMapper does that pretty well).

My Problem: I have a Class with a property of List:

public class User {
    public List<Long> listProp;//it is public only to keep the example simple
}

How can I get the correct TypeReference (or JavaType ?) so that I can map programatically a JSON String to the correct List Type, having the instance of the Class class (User.class) and the property name (listProp)? What I mean is this:

TypeReference typeReference = ...;//how to get the typeReference?
List<Long> correctList = om.readValue(jsonEntry.getValue(), typeReference);//this should return a List<Long> and not eg. a List<Integer>
like image 522
V G Avatar asked Jan 13 '23 23:01

V G


1 Answers

Have you tried the mappers constructType method?

Type genericType = User.class.getField("listProp").getGenericType();
List<Long> correctList = om.readValue(jsonEntry.getValue(), om.constructType(genericType));
like image 168
Gandalf Avatar answered Jan 20 '23 03:01

Gandalf