How to serialize Date to long using gson?

后端 未结 2 1843
情歌与酒
情歌与酒 2021-02-19 05:26

I recently switched some of our serialization from Jackson to Gson. Found out that Jackson serializes dates to longs.

But, Gson serializes Date

2条回答
  •  [愿得一人]
    2021-02-19 05:49

    First type adapter does the deserialization and the second one the serialization.

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, (JsonDeserializer) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
            .registerTypeAdapter(Date.class, (JsonSerializer) (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);
    

提交回复
热议问题