继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

[jackson]简单写下jackson反序列化泛型类的使用方法

汐鸟
关注TA
已关注
手记 1
粉丝 2
获赞 5

1.先简单看下没有泛型的处理(这里用DataBinding处理,当然网上也有很多其他方法,就不多说啦)

首先假设请求返回的json是这样:
{"status":0,"message":"miaomiao",data:[{"username":"chino","age":"13"},{"username":"kotori","age":"16"}]}

然后是2个类:

@Getter @Setter
public class Response {
    private int status;
    private String message;
    private List<User> data;
}
@Getter @Setter
public class User {
    private String username;
    private String age;
}

假如没有定义泛型类,2行代码就可以了

ObjectMapper mapper = new ObjectMapper();
Response response = mapper.readValue(json, Response.class);
//response.getData().forEach(user -> System.out.println(user.getUsername()));

2.假如把返回的类变成通用的泛型类

@Getter @Setter
public class Response<T> {
    private int status;
    private String message;
    private T data;
}

直接传class肯定是不行的,这里需要自己显式构建:

ObjectMapper mapper = new ObjectMapper();
Response<List<User>> response = mapper.readValue(json, new TypeReference<Response<List<User>>>(){});

也可以用constructParametrizedType来构建(不过这个方法源码注释写了即将标记为过时)

ObjectMapper mapper = new ObjectMapper();
JavaType userType = TypeFactory.defaultInstance().constructParametrizedType(ArrayList.class, List.class, User.class);
JavaType javaType = TypeFactory.defaultInstance().constructParametrizedType(Response.class, Response.class, userType);
Response<List<User>> response = mapper.readValue(json, javaType);
打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP