Gson dateformat解析/输出unix-timestamps [英] Gson dateformat to parse/output unix-timestamps
问题描述
我使用Gson序列化/反序列化我的pojos,并且正在寻找一种干净的方式来告诉Gson将日期属性解析/输出为unix-timestamps。
这里是我的尝试:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ gson gson = new GsonBuilder setDateFormat(U).create() ;
从PHP中输出,其中U是用于解析/输出日期的日期格式为unix-timestamps,当运行我的尝试代码时,我得到这个RuntimeException:
未知的模式字符'U'
blockquote>
我假设Gson使用SimpleDateformat,它没有定义字母U。
I可以写一个
DateTypeAdapter
,并将它注册到GsonBuilder
中,但我正在寻找一种更简洁的方式来实现这一点。只需更改DateFormat
就可以了。解决方案code> DateTypeAdapter 是要走的路。
MyDateTypeAdapter $ b
public class MyDateTypeAdapter extends TypeAdapter< Date> {
@Override
public void write(JsonWriter out,Date value)抛出IOException {
if(value == null)
out.nullValue();
else
out.value(value.getTime()/ 1000);
$ b @Override
public读取的日期(JsonReader in)抛出IOException {
if(in!= null)
return new Date(in。 nextLong()* 1000);
else
返回null;
}
}
不要忘记注册
Gson gson = new GsonBuilder()。registerTypeAdapter(Date.class,new MyDateTypeAdapter())。create() ;
I am using Gson to serialize/deserialize my pojos and currently looking for a clean way to tell Gson to parse/output date attributes as unix-timestamps. Here's my attempt:
Gson gson = new GsonBuilder().setDateFormat("U").create();
Comming from PHP where "U" is the dateformat used to parse/output date as unix-timestamps, when running my attempt code, I am getting this RuntimeException:
Unknown pattern character 'U'
I am assuming that Gson uses SimpleDateformat under the hood which doesn't define the letter "U".
I could write a
DateTypeAdapter
and register it in theGsonBuilder
but I am looking for a cleaner way to achieve that. Simply changing theDateFormat
would be great.解决方案Creating a custom
DateTypeAdapter
was the way to go.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; } }
Don't forget to register it
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,new MyDateTypeAdapter()).create();
这篇关于Gson dateformat解析/输出unix-timestamps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!