【问题标题】:Json LocalDateTIme issueJson LocalDateTIme 问题
【发布时间】:2021-09-12 14:03:39
【问题描述】:
Exception during serialization - message:  
Cannot deserialize value of type `java.time.LocalDateTime` from String "2021-05-04T09:06:27-05:00":  
Failed to deserialize java.time.LocalDateTime: 
(java.time.format.DateTimeParseException) Text '2021-05-04T09:06:27-05:00'
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", shape = JsonFormat.Shape.STRING )
    @JsonProperty("inprogress_ts")
    val inProgressTs: LocalDateTime

为什么这个@JsonFormat 模式不能解析String "2021-05-04T09:06:27-05:00"

【问题讨论】:

  • 我使用过@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", shape = JsonFormat.Shape.STRING ) 但这不起作用
  • 不是String,您可以直接转换为LocalDateTime,因为它包含偏移量(-05:00)。使用OffsetDateTime,应该可以...
  • 谢谢,成功了

标签: java json kotlin


【解决方案1】:

它不起作用,因为您使用了不合适的数据类型/类:

LocalDateTime 不考虑偏移量,它根本没有并且无法解析包含偏移量的 Strings。
您的String 包含-05:00,这将导致DateTimeParseException 被抛出。

使用合适的类:OffsetDateTime

【讨论】:

  • ZonedDateTime 也适合。
【解决方案2】:

您传递的字符串与 JsonFormat 的格式不同:

2021-05-04     T    09:06:27    -05:00
yyyy-MM-dd    'T'   HH:mm:ss    ??????

【讨论】:

    【解决方案3】:

    如果您包含区域,那么它应该可以工作。我在 kotlin 中编写了一个示例扩展函数可能会有所帮助

    fun String.convertDateString(): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH)
        val date: Date = dateFormat.parse(this) ?: Date()
        val outFormat = SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH)
        return outFormat.format(date)
    }
    

    输入:“2021-05-04T09:06:27-05:00”

    格式化响应:“2021 年 5 月 4 日”。

    实际日期:2021-05-04T16:06:27.000+0200(GMT+2:00 时区)

    【讨论】:

      【解决方案4】:

      我已经格式化如下,然后手动转换

          @JsonProperty("event_ts")
      
      
      val packedCentralTime = eventTs.withZoneSameInstant(ZoneId.of("America/Chicago")).toLocalDateTime()
      
      

      【讨论】:

        猜你喜欢
        • 2018-07-22
        • 1970-01-01
        • 2019-10-14
        • 2021-06-04
        • 2020-03-12
        • 1970-01-01
        • 2018-12-08
        • 2021-05-28
        • 1970-01-01
        相关资源
        最近更新 更多