I recently switched some of our serialization from Jackson to Gson. Found out that Jackson serializes dates to longs.
But, Gson serializes Date
First type adapter does the deserialization and the second one the serialization.
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
.registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime()))
.create();
Usage:
String jsonString = gson.toJson(objectWithDate1);
ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class);
assert objectWithDate1.equals(objectWithDate2);
You can do both direction with one type adapter:
public class DateLongFormatTypeAdapter extends TypeAdapter<Date> {
@Override
public void write(JsonWriter out, Date value) throws IOException {
if(value != null) out.value(value.getTime());
else out.nullValue();
}
@Override
public Date read(JsonReader in) throws IOException {
return new Date(in.nextLong());
}
}
Gson builder:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateLongFormatTypeAdapter())
.create();