gpt4 book ai didi

java - 如何为 java.time.LocalDateTime 自定义全局 Jackson 反序列化器

转载 作者:行者123 更新时间:2023-12-02 10:53:14 27 4
gpt4 key购买 nike

Jackson 的 JavaTimeModule 序列化/反序列化 java.time全局通用,但其默认日期时间格式是 ISO 标准,例如 2018-01-10T10:20:30对于 LocalDateTime 和 2018-01-10T10:20:30+08:00对于偏移日期时间。但我需要设置一个全局本地格式,如 2018-01-10 10:20:30对于 LocalDateTime 和 OffsetDateTime,没有 T和OffsetTime(使用本地默认OffsetTime)。我怎样才能做到这一点?

Notes: I know about @JsonFormat, @JsonSerialize and @JsonDeserialize. That is not global setting.

最佳答案

Spring 启动

    @SpringBootApplication
public class Application implements Jackson2ObjectMapperBuilderCustomizer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTimeSerializer localDateTimeSerializer = new LocalDateTimeSerializer(formatter);

builder.failOnEmptyBeans(false) // prevent InvalidDefinitionException Error
.serializerByType(LocalDateTime.class, localDateTimeSerializer);
}
}

Springboot 和 Spring 框架

    @Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTimeSerializer localDateTimeSerializer = new LocalDateTimeSerializer(formatter);
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(formatter);

JavaTimeModule module = new JavaTimeModule();
module.addSerializer(LocalDateTime.class, localDateTimeSerializer);
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
// add converter at the very front
// if there are same type mappers in converters, setting in first mapper is used.
converters.add(0, new MappingJackson2HttpMessageConverter(mapper));
}
}

希望这可以帮助你。

关于java - 如何为 java.time.LocalDateTime 自定义全局 Jackson 反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51996459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com