[xingyu.guo] feat: 指定jackson对LocalDateTime的序列化规则
This commit is contained in:
@@ -0,0 +1,24 @@
|
|||||||
|
package com.guo.learningprogresstracker.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||||
|
import com.guo.learningprogresstracker.config.serializer.LocalDateTimeSerializer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author guo
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class JacksonConfig {
|
||||||
|
@Bean
|
||||||
|
public ObjectMapper objectMapper() {
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
SimpleModule module = new SimpleModule();
|
||||||
|
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
|
||||||
|
mapper.registerModule(module);
|
||||||
|
return mapper;
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.guo.learningprogresstracker.config.serializer;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonGenerator;
|
||||||
|
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||||
|
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
public class LocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
|
||||||
|
|
||||||
|
// 定义你希望使用的日期时间格式
|
||||||
|
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");;
|
||||||
|
|
||||||
|
public LocalDateTimeSerializer() {
|
||||||
|
super(LocalDateTime.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
|
||||||
|
if (value == null) {
|
||||||
|
gen.writeNull();
|
||||||
|
} else {
|
||||||
|
// 格式化LocalDateTime为字符串
|
||||||
|
String formattedDate = value.format(formatter);
|
||||||
|
// 将格式化后的字符串写入JSON流作为一个值
|
||||||
|
gen.writeString(formattedDate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user