【问题标题】:Java Jackson Deserialize 2023-01-13T08:54:25.83-03:00Java Jackson 反序列化 2023-01-13T08:54:25.83-03:00
【发布时间】:2023-01-13 20:37:47
【问题描述】:

如何使用 Jackson 以这种格式 2023-01-13T08:54:25.83-03:00 反序列化 LocalDateTime?

我正在尝试使用注释

@JsonFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss", shape = JsonFormat.Shape.STRING)
@JsonProperty("created_at")
private LocalDateTime createdAt;

【问题讨论】:

  • 当您将模式与值进行比较时,您应该注意到两者之间存在差异。
  • 看来您输入的不是本地日期时间,而是带有偏移量的日期时间。
  • 除了 @f1sh 所写的内容:您有一个 String 表示日期和时间以及与 UTC 的偏移量,但是 LocalDateTime 将无法存储该偏移量。您应该切换到 OffsetDateTime 或解析并忽略偏移量。是的,偏移量是差异之一,但至少还有一个差异:几分之一秒。

标签: java jackson java-time


【解决方案1】:

完成了,谢谢。

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonProperty("created_at")
private LocalDateTime createdAt;

...

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

@Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return OffsetDateTime.parse( p.getText() ).toLocalDateTime();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多