使用Gson时序列化LocalDateTime
使用Java 8和Gson时,如果序列化LocalDate会得到如下的格式:
"birthday": {
"year": 1997,
"month": 11,
"day": 25
}
但我们开发的时候,一般采用的形式为:
“birthday”: “1997-11-25”
Gson是否也支持更简洁的开箱即用格式,或者我是否必须为LocalDates实现自定义序列化器?
自定义一个日期类型转换器,作为一个配置类注入Spring容器
package com.***.***.service.***.config;
import com.google.gson.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @Author
* @Date: 2020-12-04 14:42
* @Description Gson的LocalDateTime和String转化
*/
@Configuration
public class GSONConfiguration {
//序列化
final static JsonSerializer<LocalDateTime> jsonSerializerDateTime = (localDateTime, type, jsonSerializationContext)
-> new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
final static JsonSerializer<LocalDate> jsonSerializerDate = (localDate, type, jsonSerializationContext)
-> new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//反序列化
final static JsonDeserializer<LocalDateTime> jsonDeserializerDateTime = (jsonElement, type, jsonDeserializationContext)
-> LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
final static JsonDeserializer<LocalDate> jsonDeserializerDate = (jsonElement, type, jsonDeserializationContext)
-> LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
@Bean
public Gson create() {
return new GsonBuilder()
.setPrettyPrinting()
/* 更改先后顺序没有影响 */
.registerTypeAdapter(LocalDateTime.class, jsonSerializerDateTime)
.registerTypeAdapter(LocalDate.class, jsonSerializerDate)
.registerTypeAdapter(LocalDateTime.class, jsonDeserializerDateTime)
.registerTypeAdapter(LocalDate.class, jsonDeserializerDate)
.create();
}
}
使用
1.注入Gson
@Autowired
Gson gson;
2.使用gson反序列化
MessageCommon messageCommon = (MessageCommon)gson.fromJson(message, MessageCommon.class);