如何使用gson将Date序列化为long?

Ali*_*aka 11 java json date jackson gson

我最近将一些序列化切换JacksonGson.发现杰克逊将日期序列化为多头.

但是,Gson默认将Dates序列化为字符串.

使用Gson时如何将日期序列化为多头?谢谢.

Ali*_*aka 20

第一种类型的适配器执行反序列化,第二种类型适配器执行序列化.

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();
Run Code Online (Sandbox Code Playgroud)

用法:

String jsonString = gson.toJson(objectWithDate1);
ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class);
assert objectWithDate1.equals(objectWithDate2);
Run Code Online (Sandbox Code Playgroud)


Dan*_*ári 10

你可以用一种类型的适配器做两个方向:

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

}
Run Code Online (Sandbox Code Playgroud)

Gson建设者:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Date.class, new DateLongFormatTypeAdapter())
        .create();
Run Code Online (Sandbox Code Playgroud)