【问题标题】:Mapping Date Strings to Dates including Time with Jackson in Spring将日期字符串映射到包括杰克逊在春季的时间在内的日期
【发布时间】:2017-01-23 13:02:01
【问题描述】:

我正在使用 Spring Boot 1.4 和以下作品。我定义了这个@Bean

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    mapper.registerModule(new JodaModule());
    return new MappingJackson2HttpMessageConverter(mapper);
}

我已经定义了这个 DTO:

public class ReportRequest implements Serializable {
    private LocalDate startDate;
    private LocalDate endDate;
    // additional fields and getters/setters omitted
}

我将此数据提交到带有@RequestBody ReportRequest 的控制器,请求正文中包含以下json:

{
    "startDate": "2016-09-01",
    "endDate": "2016-09-12"
}

效果很好。但是,我还需要包括时间。所以我把所有东西都改成了这样:

mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

private LocalDateTime startDate;
private LocalDateTime endDate;

{
    "startDate": "2016-09-01 02:00:00",
    "endDate": "2016-09-12 23:59:59"
}

这不起作用。我得到:

Could not read document: Invalid format: \"2016-09-01 02:00:00\" is malformed at \" 02:00:00\" (through reference chain: com.hightouchinc.dto.ReportRequest[\"startDate\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid format: \"2016-09-01 02:00:00\" is malformed at \" 02:00:00\" (through reference chain: com.hightouchinc.dto.ReportRequest[\"startDate\"])

更新:我修改了以下内容:

mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

并且可以发送"2016-09-01T02:00:00" 并且它可以工作。但是从两者中删除T 仍然会中断。

【问题讨论】:

    标签: spring date spring-boot jackson jodatime


    【解决方案1】:

    LocalDateTimeDeserializer 似乎不尊重传递给setDateFormat() 的值,如JodaModule 所示:

    addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
    

    你可以做的是在注册之前覆盖模块中的默认反序列化器:

    JodaModule jodaModule = new JodaModule();
    JacksonJodaDateFormat format = new JacksonJodaDateFormat("yyyy-MM-dd HH:mm:ss");
    jodaModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(format)));
    mapper.registerModule(jodaModule);
    

    这应该使用正确的模式来反序列化您的 LocalDateTime 实例。

    【讨论】:

    • 这是个好主意,但JacksonJodaDateFormat 不接受字符串。它需要一个 DateTimeFormatter,所以我试图确定如何正确包装它。
    • 确实如此。您可以使用 DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 从字符串创建它
    • 你不能,因为 DateTimeFormat 来自 java.text,而 JacksonJodaDateFormat 想要一个 joda 时间 DateTimeFormatter,这不一样。
    • 我还必须添加 mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); 否则我会将日期划分为列表。但其他一切都很好。谢谢。
    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多