问题
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 the GsonBuilder
but I am looking for a cleaner way to achieve that. Simply changing the DateFormat
would be great.
回答1:
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();
回答2:
Time stamps are just long
's, so you can use that in your POJO. Or use Long
to get a null
if the field is missing.
class myPOJO {
Long myDate;
}
来源:https://stackoverflow.com/questions/41348055/gson-dateformat-to-parse-output-unix-timestamps