0

Have a java object with a LocalDateTime property that I want to serialize and deserialize with gson. I am using ISO_INSTANT as the format for datetime in the json output

Have tried creating a TypeAdaptor for GSON with the help from this post

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

But get "Unsupported field: InstantSeconds"

Maybe I have gotten the date conversion messed up?

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"
        }
}
Anders
  • 37
  • 1
  • 6

1 Answers1

0

Your issue is unrelated to Gson, it also occurs when just running the date formatting code:

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

Exception:

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)

It appears (based on this comment) that you should convert the LocalDateTime to a ZonedDateTime before formatting it.

Marcono1234
  • 5,856
  • 1
  • 25
  • 43