Java泛型 | Jackson TypeReference获取泛型类型信息
前言
Jackson是一个比较流行的Json序列化和反序列化框架。本文以Jackson为例介绍TypeReference实现涉及泛型的反序列化,及TypeReference的实现原理。对于获取泛型类型信息的场景,TypeReference是一个可以参考的通用解决方案。
实例
Jackson ObjectMapper的readValue可以将Json字符串反序列化为Java对象。如下例中将
[{"id":null,"name":" ","age":500,"gender":false,"email":"email","employed":true,"salary":10}]
反序列化为
List<UserResource>
类型。
Json字符串:
[{
"id": null,
"name": " ",
"age": 500,
"gender": false,
"email": "email",
"employed": true,
"salary": 10
}]
UserResource实体类:
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserResource {
private UUID id;
private String name;
private int age;
private boolean gender;
private String email;
private boolean employed;
private BigDecimal salary;