手记

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

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人推荐
随时随地看视频
慕课网APP