使用gson和ISO_INSTANT序列化LocalDateTime生成错误:不支持的字段

eni9jsuy  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(187)

我有一个java对象,该对象具有LocalDateTime属性,我希望使用gson对该属性进行序列化和反序列化。
在这篇文章的帮助下,尝试为GSON创建TypeAdaptor
https://stackoverflow.com/a/39193077/1196875
但得到“不支持的字段:瞬时秒数”
也许我把日期转换搞砸了?

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"
        }
}
vu8f3i0k

vu8f3i0k1#

您的问题与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)

根据此注解,似乎应该在格式化LocalDateTime之前将其转换为ZonedDateTime

相关问题