Spring Boot OffsetDateTime 返回时转为 String

Spring Boot About 1,195 words

需求

PostgreSQL中存储的带时区的时间字段,对应Java中为OffsetDateTimeController返回时没有对应的处理方法,会抛出异常。

代码

主要是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: 997 · Posted: 2024-04-11

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh