java - serialize - spring boot jackson date format




Serialize Java 8 LocalDate as yyyy-mm-dd with Gson (2)

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) {
            return null;
        } else {
            return LocalDate.parse(jsonReader.nextString());
        }
    }
}

Registered as @Drux says:

return new GsonBuilder()
        .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
        .create();

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.)


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




gson