How to serialize Date to long using gson?

a 夏天 提交于 2019-12-12 08:27:16

问题


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

But, Gson serializes Dates to strings by default.

How do I serialize dates to longs when using Gson? Thanks.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/41979086/how-to-serialize-date-to-long-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!