“LocalDateTime”以数组格式表示。

huangapple go评论105阅读模式
英文:

LocalDateTime is representing in array format

问题

我正在使用Spring Boot 2.2.6和Jackson 2.10.3,配合Java 8使用。项目中始终使用LocalDateTime对象。Jackson无法正确解析LocalDateTime(或者可能是它的默认格式),并且将日期在JSON响应中以数组格式发送,如下所示:

            "createdDate": [
                2020,
                8,
                31,
                0,
                0,
                0,
                80000000
            ]

正如在https://stackoverflow.com/questions/29956175/json-java-8-localdatetime-format-in-spring-boot中所述,Spring Boot 2在类路径上已经默认使用jackson-datatype-jsr310:2.10.3。我希望整个项目中的日期在JSON中表示为2020-03-31:00。第一个解决方案在上面的链接中无效。在那之后,我尝试了@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")));
            };
        }
    }

控制器

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        User getUser(){
            User user = new User();
            user.createdDate = LocalDateTime.now();
            return user;
        }
    
    }

是否有任何全局级别的操作可以执行,以便项目中的每个日期都以字符串格式(例如2020-09-01)进行序列化?

欢迎提出任何建议。
英文:

I am using spring boot 2.2.6 and Jackson 2.10.3 with Java 8. I am using localdatetime objects through out my project. Jackson is not able to parse LocalDateTime properly (or may be it's default format) and sending date in json response as in array format like below

        "createdDate": [
2020,
8,
31,
0,
0,
0,
80000000
]

As described in https://stackoverflow.com/questions/29956175/json-java-8-localdatetime-format-in-spring-boot , Spring boot 2 has already default jackson-datatype-jsr310:2.10.3 on classpath. I want dates to represent in json as 2020-03-31:00 in whole project. First solution doesn't work in the above link. After that i have tried @JsonSerialize annotation and it works but i don't want to apply on each and every class. So also tried to override object mapper but it didn't work

@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;
}

Also tried to customize Jackson2ObjectMapperBuilder, but still have date in array format

@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;
}

Tried with also 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")));
};
}
}

Contoller

@RestConroller
@RequestMapping("/user")
UserController {
User getUser(){
User user = new User()
user.createdDate = LocalDateTime.now();
return user;
}
}

is there anything i can do at global level, so every date in the project will be serialized as in string format like 2020-09-01 ?

Any suggestion will be helpful.

答案1

得分: 20

罪魁祸首是@EnableWebMVC。我的一个CORS类上有@EnableWebMVC注解。这会禁用Spring Boot的自动配置,也会覆盖映射器配置。这将不允许您覆盖对象映射器的配置。通过移除@EnableMVC注解,现在一切正常。在SpringBoot2中,我们不需要显式地进行与日期序列化相关的任何配置,它会自动解析Java 8日期,格式为**"yyyy-mm-dd"**。

英文:

The culprit was @EnableWebMVC. One of my cors class was having @EnableWebMVC annotation. This was disabling the spring boot auto configuration and also overriding the mapper confiiguration. This won't let you to override the configuration of object mapper. By removing @EnableMVC annotation, this is working fine now. In SpringBoot2, we don't need to do any configuration explicitly related to date serialization, it will automatically parse the java 8 dates in "yyyy-mm-dd" format.

答案2

得分: 2

在User模型的日期字段上使用以下的Jackson注解:

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
英文:

use below Jackson annotation on date fields of User model :

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")

答案3

得分: 1

创建一个Jackson2ObjectMapperBuilderCustomizer bean:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return builder -> {
        builder.simpleDateFormat(dateTimeFormat);
        builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
        builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
    };
}

application.properties中添加属性spring.jackson.serialization.write_dates_as_timestamps=false,或者您也可以在Jackson2ObjectMapperBuilderCustomizer中以编程方式进行设置。

英文:

Create a Jackson2ObjectMapperBuilderCustomizer bean:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.simpleDateFormat(dateTimeFormat);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
};
}

Add property spring.jackson.serialization.write_dates_as_timestamps=false to application.properties or you can also do it programmatically in the Jackson2ObjectMapperBuilderCustomizer.

huangapple
  • 本文由 发表于 2020年9月1日 14:41:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63682619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定