I am using Java 8 and the latest RELEASE
version (via Maven) of Gson. If I serialize a LocalDate
I get something like this
"birthday": { "year": 1997, "month": 11, "day": 25 }
where I would have preferred "birthday": "1997-11-25"
. Does Gson also support the more concise format out-of-the-box, or do I have to implement a custom serializer for LocalDate
s?
(I've tried gsonBuilder.setDateFormat(DateFormat.SHORT)
, but that does not seem to make a difference.)
Until further notice, I have implemented a custom serializer like so:
class LocalDateAdapter implements JsonSerializer<LocalDate> { public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // "yyyy-mm-dd" } }
It can be installed e.g. like so:
Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create();
I use the following, supports read/write and null values:
class LocalDateAdapter extends TypeAdapter<LocalDate> { @Override public void write(final JsonWriter jsonWriter, final LocalDate localDate) throws IOException { if (localDate == null) { jsonWriter.nullValue(); } else { jsonWriter.value(localDate.toString()); } } @Override public LocalDate read(final JsonReader jsonReader) throws IOException { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); return null; } else { return LocalDate.parse(jsonReader.nextString()); } } }
Registered as @Drux says:
return new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create();
EDIT 2019-04-04 A simpler implementation
private static final class LocalDateAdapter extends TypeAdapter<LocalDate> { @Override public void write( final JsonWriter jsonWriter, final LocalDate localDate ) throws IOException { jsonWriter.value(localDate.toString()); } @Override public LocalDate read( final JsonReader jsonReader ) throws IOException { return LocalDate.parse(jsonReader.nextString()); } }
Which you can add null
support to by registering the nullSafe()
wrapped version:
new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With