Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

java - How to use Jackson's TypeReference with generics?

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>>() {
    });
}

And UserDto looks like this:

@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 UserDto class, and replacing it with a generic.

Is it possible? And How?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...