【问题标题】:Serialise LocalDateTime with gson and ISO_INSTANT generates error: Unsupported field使用 gson 和 ISO_INSTANT 序列化 LocalDateTime 生成错误:不支持的字段
【发布时间】:2021-10-13 11:08:41
【问题描述】:

有一个带有 LocalDateTime 属性的 java 对象,我想用 gson 对其进行序列化和反序列化。 我在 json 输出中使用 ISO_INSTANT 作为日期时间的格式

已尝试在这篇文章的帮助下为 GSON 创建一个 TypeAdaptor

https://stackoverflow.com/a/39193077/1196875

但得到“不支持的字段:InstantSeconds”

也许我搞砸了日期转换?

class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
            @Override
            public JsonElement serialize(LocalDateTime date, Type typeOfSrc, JsonSerializationContext context) {
                return new JsonPrimitive(
                        DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()).withLocale(Locale.getDefault()).format(date)); // "yyyy-mm-ddThhMMssZ"
        }
}

【问题讨论】:

  • 请包含完整的堆栈跟踪。

标签: java json gson java-time


【解决方案1】:

您的问题与Gson无关,仅在运行日期格式代码时也会出现:

LocalDateTime date = LocalDateTime.now()
DateTimeFormatter.ISO_INSTANT
  .withZone(ZoneId.systemDefault())
  .withLocale(Locale.getDefault())
  .format(date);

例外:

Exception java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
    at LocalDate.get0 (LocalDate.java:709)
    at LocalDate.getLong (LocalDate.java:688)
    at LocalDateTime.getLong (LocalDateTime.java:718)
    at DateTimePrintContext$1.getLong (DateTimePrintContext.java:205)
    at DateTimePrintContext.getValue (DateTimePrintContext.java:308)
    at DateTimeFormatterBuilder$InstantPrinterParser.format (DateTimeFormatterBuilder.java:3459)
    at DateTimeFormatterBuilder$CompositePrinterParser.format (DateTimeFormatterBuilder.java:2402)
    at DateTimeFormatter.formatTo (DateTimeFormatter.java:1849)
    at DateTimeFormatter.format (DateTimeFormatter.java:1823)
    at (#5:1)

看起来(基于this comment)您应该在格式化之前convert the LocalDateTime to a ZonedDateTime

【讨论】:

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