将字符串日期映射到 LocalDateTime 时发生 MessageConversionException

MessageConversionException occurred when mapping string date to LocalDateTime

我有一个监听主题的队列,我的监听器接收到一个 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));
    }
}

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

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

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

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

    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 可以。

Link

Wikipedia article: ISO 8601

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

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