java 如何将 Jackson 的 TypeReference 与泛型一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34578452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Hymanson's TypeReference with generics?
提问by Mark Korzhov
For json mapping I use the following method:
对于 json 映射,我使用以下方法:
public static <T> T mapJsonToObject(String json, T dtoClass) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, new TypeReference<RestResponse<UserDto>>() {
});
}
And UserDtolooks like this:
而UserDto看起来是这样的:
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDto {
@JsonProperty("items")
private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
I want to improve this method of mapping without being attached to a UserDtoclass, and replacing it with a generic.
我想在不附加到UserDto类的情况下改进这种映射方法,并将其替换为泛型。
Is it possible? And How?
是否可以?如何?
Thanks.
谢谢。
回答by StaxMan
TypeReference
requires you to specify parameters statically, not dynamically, so it does not work if you need to further parameterize types.
TypeReference
要求您静态地而不是动态地指定参数,因此如果您需要进一步参数化类型,它不起作用。
What I think you need is JavaType
: you can build instances dynamically by using TypeFactory
. You get an instance of TypeFactory
via ObjectMapper.getTypeFactory()
. You can also construct JavaType
instances from simple Class
as well as TypeReference
.
我认为您需要的是JavaType
:您可以使用TypeFactory
. 你得到一个TypeFactory
via的实例ObjectMapper.getTypeFactory()
。您还可以JavaType
从 simpleClass
和TypeReference
.
回答by Marcel Baumann
One approach will be to define a Hymanson JavaTyperepresenting a list of items of type clazz. You still need to have access to the class of the generic parameter at runtime. The usual approach is something like
一种方法是定义一个 Hymanson JavaType,表示clazz类型的项目列表。您仍然需要在运行时访问泛型参数的类。通常的方法是这样的
<T> class XX { XX(Class<T> clazz, ...) ... }
to pass the class of the generic parameter into the generic class at construction.
在构造时将泛型参数的类传递到泛型类中。
Upon access to the Class clazzvariable you can construct a Hymanson JavaType representing, for example, a list of items of class clazzwith the following statement.
在访问 Class clazz变量时,您可以构造一个 Hymanson JavaType 表示,例如,使用以下语句表示类clazz的项目列表。
JavaType itemType = mapper.getTypeFactory().constructCollectionType(List.class, clazz);
I hope it helped. I am using this approach in my own code.
我希望它有所帮助。我在自己的代码中使用这种方法。