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);
点击查看更多内容
3人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦