Gson dateformat解析/输出unix-timestamps

Ani*_*oin 8 android date-format unix-timestamp gson

我正在使用Gson序列化/反序列化我的pojos,并且目前正在寻找一种干净的方式来告诉Gson将日期属性解析/输出为unix-timestamps.这是我的尝试:

    Gson gson = new GsonBuilder().setDateFormat("U").create();
Run Code Online (Sandbox Code Playgroud)

来自PHP,其中"U"是用于解析/输出日期的dateformat作为unix-timestamps,当运行我的尝试代码时,我得到这个RuntimeException:

未知的模式字符'U'

我假设Gson在引擎盖下使用SimpleDateformat,但没有定义字母"U".

我可以写一个DateTypeAdapter并注册它,GsonBuilder但我正在寻找一种更清洁的方法来实现这一目标.简单地改变它DateFormat会很棒.

Ani*_*oin 17

创建自定义DateTypeAdapter是最佳选择.

MyDateTypeAdapter

public class MyDateTypeAdapter extends TypeAdapter<Date> {
    @Override
    public void write(JsonWriter out, Date value) throws IOException {
        if (value == null)
            out.nullValue();
        else
            out.value(value.getTime() / 1000);
    }

    @Override
    public Date read(JsonReader in) throws IOException {
        if (in != null)
            return new Date(in.nextLong() * 1000);
        else
            return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

别忘了注册!

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

  • @AnixPasBesoin你在读取覆盖时出错了.必须是`return new Date(in.nextLong()*1000);`Unix时间戳以秒为单位,Date构造函数需要毫秒. (2认同)