我正在使用Spring Boot 2.2.6和Jackson 2.10.3,以及Java 8。在项目中,我一直在使用LocalDateTime对象。然而,Jackson不能正确地解析LocalDateTime(或者它的默认格式),并将日期作为数组格式发送到JSON响应中,类似于下面的格式:
"createdDate": [
2020,
8,
31,
0,
0,
0,
80000000
]
如JSON Java 8 LocalDateTime format in Spring Boot所述,Spring Boot 2已默认在类路径上具有jackson-datatype-jsr310:2.10.3。我想让整个项目的日期以2020-03-31:00的形式表示为json。第一种解决方案在上面的链接中不起作用。之后,我尝试了@JsonSerialize注释,并且它有效,但我不想在每个类上应用它。因此,还尝试了覆盖对象映射器,但它没有起作用。
@Primary
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
SimpleModule module = new SimpleModule("my custom date serializer");
module.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer());
mapper.registerModule(module);
return mapper;
}
我也尝试自定义Jackson2ObjectMapperBuilder,但仍然有日期以数组格式显示。
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
SimpleModule module = new SimpleModule("my custom date serializer");
module.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer());
builder.modulesToInstall(modules)
return builder;
}
还尝试了使用Jackson2ObjectMapperBuilderCustomizer
@Configuration
public class JacksonConfiguration {
@Primary
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
};
}
}
控制器
@RestConroller
@RequestMapping("/user")
UserController {
User getUser(){
User user = new User()
user.createdDate = LocalDateTime.now();
return user;
}
}
在全局范围内是否有任何措施可以使项目中的每个日期都以字符串格式进行序列化,例如2020-09-01?
任何建议都将非常有用。