问题描述
我正在使用Jackson解析对象.有时我需要对象列表.
I am using Jackson to parse object. sometime I need list of objects.
当我这样使用时
List<MyObject> mapper.readValue(file , new TypeReference<MyObject>() {})
但是当我这样使用它时,它就不起作用了
but when I am using it like this its not working
public class JsonMocksRepository<T>{
public T getObject() throws Exception{
return mapper.readValue(file ,new TypeReference<T>());
}
}
我需要做什么?基本上,我想使用泛型来获取正确的类
What I need to do ?Basically I want to use generics to get the right class
推荐答案
这是因为类型擦除.在运行时没有可用的T表示的实际类型的信息,因此您的TypeReference
实际上就是TypeReference<Object>
.
This is because of type erasure. There is no information about the actual type represented by T available at runtime, so your TypeReference
will be effectively be simply TypeReference<Object>
.
如果要使用JsonMocksRepository
的通用实例,则需要在构造时注入TypeReference
:
If you want a generic instance of JsonMocksRepository
, you will need to inject the TypeReference
at construction time:
public class JsonMocksRepository<T>{
private final TypeReference<T> typeRef;
public JsonMocksRepository(TypeReference<T> typeRef) {
this.typeRef = typeRef;
}
public T getObject() throws Exception{
return mapper.readValue(file, typeRef);
}
}
这篇关于杰克逊解析器到Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!