【问题标题】:Jackson deserialize LocalDateTimeJackson 反序列化 LocalDateTime
【发布时间】:2021-01-19 05:41:01
【问题描述】:

我有一个时间字段值,如下所示:

2020-10-01T15:30:27.4394205+03:00

我不知道如何表示为日期格式。

我需要将其反序列化为 LocalDateTime 字段。

我试过这样;

   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
    private LocalDateTime timestamp;

但它不起作用。我怎样才能反序列化它? 顺便说一句,我正在使用弹簧靴。并且这个值来自于控制器请求体。

【问题讨论】:

    标签: spring-mvc jackson date-format jackson-databind


    【解决方案1】:
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX")
    private LocalDateTime timestamp;
    

    【讨论】:

    • 谢谢,我可以通过这种方式反序列化,但我知道我会丢失时区。所以我决定使用 OffsetDateTime。
    • 最好转换UTC,当需要显示时,可以计算本地日期时间
    【解决方案2】:

    将模式替换为pattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME

    您的日期时间字符串已采用DateTimeFormatter.ISO_OFFSET_DATE_TIME 指定的格式,这是OffsetDateTime#parse 使用的默认格式。

    演示:

    import java.time.LocalDateTime;
    import java.time.OffsetDateTime;
    
    public class Main {
        public static void main(String[] args) {
            String dateTimeStr = "2020-10-01T15:30:27.4394205+03:00";
    
            // Parse the date-time string into OffsetDateTime
            OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr);
            System.out.println(odt);
    
            // LocalDateTime from OffsetDateTime
            LocalDateTime ldt = odt.toLocalDateTime();
            System.out.println(ldt);
        }
    }
    

    输出:

    2020-10-01T15:30:27.439420500+03:00
    2020-10-01T15:30:27.439420500
    

    【讨论】:

    • 我从你的回答中认识到,如果我使用 LocalDateTime,我将丢失区域/偏移量,所以我决定使用 OffsetDateTime 类型,所以它总是对 UTC 进行反序列化,谢谢。
    【解决方案3】:

    为它写一个自定义的反序列化器:

    @Log4j2
    public class CustomLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
    
     public CustomLocalDateTimeDeserializer() {
        this(null);
    }
        private CustomLocalDateTimeDeserializer(Class<LocalDateTime> t) {
            super(t);
        }
    
        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            String date = jsonParser.getText();
            try {
                return LocalDateTime.parse(date);
            } catch (Exception ex) {
                log.debug("Error while parsing date: {} ", date, ex);
                throw new RuntimeException("Cannot Parse Date");
            }
        }
    }
    

    现在,使用反序列化器:

     @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
     @JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
     private LocalDateTime timestamp;
    

    同样,如果需要序列化,也可以自己编写一个自定义的序列化器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-16
      • 2019-11-27
      • 2021-03-30
      • 1970-01-01
      • 2017-09-15
      • 2019-07-16
      • 2016-09-07
      • 1970-01-01
      相关资源
      最近更新 更多