Spring Boot OffsetDateTime 返回时转为 String
Spring Boot About 1,195 words需求
PostgreSQL
中存储的带时区的时间字段,对应Java
中为OffsetDateTime
,Controller
返回时没有对应的处理方法,会抛出异常。
代码
主要是simpleModule.addSerializer
添加OffsetDateTime
转为String
的处理方式JsonSerializer
。
@Configuration
public class ObjectMapperConfig {
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(OffsetDateTime.class, new JsonSerializer<>() {
@Override
public void serialize(OffsetDateTime o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(DateTool.format(o));
}
});
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
public class DateTool {
private static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(FORMAT);
public static String format(OffsetDateTime offsetDateTime) {
return FORMATTER.format(offsetDateTime.atZoneSameInstant(ZoneId.systemDefault()));
}
}
Views: 1,069 · Posted: 2024-04-11
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...