Search code examples
javagson

Serialize Java 8 LocalDate as yyyy-mm-dd with 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.)


Solution

  • 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();