Gson 日期格式为 serialize/deserialize unix-timestamps

Gson dateformat to serialize/deserialize unix-timestamps

我正在使用 Gson 来 serialize/deserialize 我的 pojos,目前正在寻找一种干净的方法来告诉 Gson parse/output 日期属性作为 unix 时间戳。 这是我的尝试:

Gson gson = new GsonBuilder().setDateFormat("U").create();

来自 PHP,其中“U”是用于 serialize/deserialize 日期作为 unix 时间戳的日期格式,当 运行 我的尝试代码时,我是 RuntimeException :

Unknown pattern character 'U'

我假设 Gson 在未定义字母“U”的情况下使用 SimpleDateformat

我可以实现自定义 DateTypeAdapter,但我正在寻找一种更简洁的方法来实现它。只需更改 DateFormat 就好了。

时间戳只是 long 的,因此您可以在 POJO 中使用它。或者如果该字段缺失,则使用 Long 得到 null

class myPOJO {
    Long myDate;
}

创建自定义 TypeAdapterUnixTimestampAdapter)是正确的选择。

UnixTimestampAdapter

public class UnixTimestampAdapter extends TypeAdapter<Date> {

    @Override
    public void write(JsonWriter out, Date value) throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }
        out.value(value.getTime() / 1000);
    }

    @Override
    public Date read(JsonReader in) throws IOException {
        if (in == null) {
            return null;
        }
        return new Date(in.nextLong() * 1000);
    }

}

现在,您必须选择(取决于您的用例):

1 - 如果您想在所有日期字段上应用此序列化,请在创建 Gson 实例时注册 UnixTimestampAdapter

Gson gson = new GsonBuilder()
                   .registerTypeAdapter(Date.class, new UnixTimestampAdapter())
                   .create();

2 - 如果您希望它仅应用于某些特定字段,或者使用 @JsonAdapter 注释您的日期字段(如 @Marcono1234 所建议)。

class Person {
    @JsonAdapter(UnixTimestampAdapter.class)
    private Date birthday;
}