java jackson 泛型,如何使用Jackson的TypeReference和泛型?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值