Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Java 8 LocalDate as yyyy-mm-dd with Gson

Tags:

java

gson

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 LocalDates?

(I've tried gsonBuilder.setDateFormat(DateFormat.SHORT), but that does not seem to make a difference.)

like image 384
Drux Avatar asked Aug 28 '16 15:08

Drux


2 Answers

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(); 
like image 87
Drux Avatar answered Sep 18 '22 14:09

Drux


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()) 
like image 42
Sam Barnum Avatar answered Sep 16 '22 14:09

Sam Barnum