Serialise LocalDateTime with gson and ISO_INSTANT generates error: Unsupported field

Serialise LocalDateTime with gson and ISO_INSTANT generates error: Unsupported field

有一个带有 LocalDateTime 属性 的 java 对象,我想用 gson 对其进行序列化和反序列化。 我在 json 输出

中使用 ISO_INSTANT 作为日期时间的格式

已尝试在此 post

的帮助下为 GSON 创建 TypeAdaptor

但是得到“不受支持的字段: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"
        }
}

您的问题与 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.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) that you should convert the LocalDateTime to a ZonedDateTime格式化前