For json mapping I use the following method:
public static T mapJsonToObject(String json, T dtoClass) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, new TypeReference>() {
});
}
And UserDto looks like this:
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDto {
@JsonProperty("items")
private List userList;
public List getUserList() {
return userList;
}
public void setUserList(List userList) {
this.userList = userList;
}
}
I want to improve this method of mapping without being attached to a UserDto class, and replacing it with a generic.
Is it possible? And How?
Thanks.
解决方案
TypeReference requires you to specify parameters statically, not dynamically, so it does not work if you need to further parameterize types.
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.