And*_*i I 3 java type-erasure jackson
Java通常会删除Generics编译中的数据,但是有可能获得这些信息(杰克逊ObjectMapper做得非常好).
我的问题:我有一个具有List属性的类:
public class User {
public List<Long> listProp;//it is public only to keep the example simple
}
Run Code Online (Sandbox Code Playgroud)
我如何获得正确的TypeReference(或JavaType?),以便我可以以编程方式将JSON字符串映射到正确的列表类型,具有Class类的实例(User.class)和属性名称(listProp)?我的意思是:
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>
Run Code Online (Sandbox Code Playgroud)
你试过过mappers constructType方法吗?
Type genericType = User.class.getField("listProp").getGenericType();
List<Long> correctList = om.readValue(jsonEntry.getValue(), om.constructType(genericType));
Run Code Online (Sandbox Code Playgroud)