The adapter of the first type performs deserialization, and the second serializes.
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();
Using:
String jsonString = gson.toJson(objectWithDate1); ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class); assert objectWithDate1.equals(objectWithDate2);
source share