【问题标题】:MessageConversionException occurred when mapping string date to LocalDateTime将字符串日期映射到 LocalDateTime 时发生 MessageConversionException
【发布时间】:2020-06-17 15:34:58
【问题描述】:

我有一个侦听主题的队列,并且我的侦听器接收到 DTO。 我需要将字符串解析为LocalDateTime,但出现此错误

org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Text '2020-06-18 11:12:46' could not be parsed at index 10

这是消息详情

{"id":444, "details":{"TYPE":[1]},"dateOccurred":"2020-06-18 11:12:46"}"] 

这是我在 DTO 中的设置方式

public class PlanSubscriptionDto {
    private Long id;

    private Map<String, List<Long>> details;

    private LocalDateTime dateOccurred;

    public void setDateOccurred(String dateTime) {
        this.dateOccurred = LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_DATE_TIME);
//ive also tried this
//this.dateOccurred = LocalDateTime.parse(dateTime, DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG));
    }
}

感谢您的帮助! 任何建议都会很棒。

【问题讨论】:

    标签: java spring-boot localdatetime


    【解决方案1】:

    使用格式模式字符串来定义格式。

    public class PlanSubscriptionDto {
        private static final DateTimeFormatter FORMATTER
                = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    
        private Long id;
    
        private Map<String, List<Long>> details;
    
        private LocalDateTime dateOccurred;
    
        public void setDateOccurred(String dateTime) {
            this.dateOccurred = LocalDateTime.parse(dateTime, FORMATTER);
        }
    }
    

    为什么你的代码不起作用?

    ISO 8601 格式在日期和时间之间有一个T。您的日期时间字符串中没有 T,因此 DateTimeFormatter.ISO_DATE_TIME 无法解析它。

    变体

    现在我们已经完成了,我想展示几个其他选项。口味不同,所以我不知道你最喜欢哪一种。

    您可以输入T 以获得ISO 8601 格式。那么您将不需要显式格式化程序。单参数 LocalDateTime.parse() 解析 ISO 8601 格式。

        public void setDateOccurred(String dateTime) {
            dateTime = dateTime.replace(' ', 'T');
            this.dateOccurred = LocalDateTime.parse(dateTime);
        }
    

    或者坚持格式化器以及日期和时间之间的空格,我们可以用这种更冗长的方式定义格式化器:

        private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
                .append(DateTimeFormatter.ISO_LOCAL_DATE)
                .appendLiteral(' ')
                .append(DateTimeFormatter.ISO_LOCAL_TIME)
                .toFormatter();
    

    我们从额外的代码行中得到的结果是 (1) 更多地重用内置格式化程序 (2) 这个格式化程序将接受没有秒的时间和只有几分之一秒的时间,因为 DateTimeFormatter.ISO_LOCAL_TIME 可以。

    链接

    Wikipedia article: ISO 8601

    【讨论】:

    • 非常感谢! -_- 一开始我以为我的映射有问题。
    【解决方案2】:

    我刚刚了解到这也是解析的一个选项:)

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "uuuu-MM-dd HH:mm:ss")
    private LocalDateTime dateOccurred;
    

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 2012-08-21
      • 2020-01-03
      • 1970-01-01
      相关资源
      最近更新 更多