2019独角兽企业重金招聘Python工程师标准>>>
Jackson泛型序列化和反序列化问题
基础数据类型序列化和反序列化
// 省略getter/setter/toString 方法
public class Person {
private long id;
@JsonProperty("Career_description")
private String description;
@JsonProperty("birth_name")
private String name;
//Date类型的处理方式,格式化输出
@JsonProperty("date")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm")
private Date date;
}
```
public class JsonTest {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Person person = new Person();
person.setId(1);
person.setDescription("person description");
person.setName("kenny");
person.setDate(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
String jsonString = "null";
try {
jsonString= mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(jsonString);
try {
Person deserialized = mapper.readValue(jsonString,Person.class);
System.out.println(deserialized.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
//output: { "id" : 1, "Career_description" : "person description", "birth_name" : "kenny", "date" : "2018-10-23 16:48" } Person{id=1, description='person description', name='kenny', date=Tue Oct 23 16:48:00 CST 2018}
对于简单的数据类型,jackson能够很方便跟json字符串进行序列化与反序列化,对于泛型情况需要`TypeReference`处理
#### 基础数据类型序列化和反序列化
```java
// 省略getter/setter/toString 方法
public class User {
private String username;
private String age;
}
// 省略getter/setter/toString 方法
// 1. 将List泛型化
public class Response {
private int status;
private String message;
private T data;
}
public class ResponseJson {
public static void main(String[] args) {
User user1 = new User();
user1.setAge("16");
user1.setUsername("kenny");
User user2 = new User();
user2.setAge("20");
user2.setUsername("kai");
List list = new ArrayList<>();
list.add(user1);
list.add(user2);
Response response = new Response();
response.setData(list);
response.setMessage("get message");
response.setStatus(1000);
ObjectMapper mapper = new ObjectMapper();
String json = null;
try {
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
try {
// 2. TypeReference指定具体的数据类型
Response> response1 = mapper.readValue(json,new TypeReference>>(){});
System.out.println(response1.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
//output
{
"status" : 1000,
"message" : "get message",
"data" : [ {
"username" : "kenny",
"age" : "16"
}, {
"username" : "kai",
"age" : "20"
} ]
}
Response{status=1000, message='get message', data=[User{username='kenny', age='16'}, User{username='kai', age='20'}]}
Process finished with exit code 0
[reference] https://www.imooc.com/article/20950