问题描述
对于 json 映射,我使用以下方法:
For json mapping I use the following method:
public static <T> T mapJsonToObject(String json, T dtoClass) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, new TypeReference<RestResponse<UserDto>>() {
});
}
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;
}
}
我想改进这种映射方法,而不是附加到 UserDto 类,而是将其替换为泛型.
I want to improve this method of mapping without being attached to a UserDto class, and replacing it with a generic.
有可能吗?以及如何?
谢谢.
推荐答案
TypeReference
要求您静态指定参数,而不是动态指定参数,因此如果您需要进一步参数化类型,它不起作用.
TypeReference
requires you to specify parameters statically, not dynamically, so it does not work if you need to further parameterize types.
我认为您需要的是 JavaType
:您可以使用 TypeFactory
动态构建实例.您可以通过 ObjectMapper.getTypeFactory()
获得 TypeFactory
的实例.您还可以从简单的 Class
以及 TypeReference
构建 JavaType
实例.
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
.
这篇关于如何将 Jackson 的 TypeReference 与泛型一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!