Gson dateformat for parsing / output unix-timestamps

I use Gson to serialize / deserialize my pojos and am currently looking for a clean way to tell Gson to parse / infer date attributes as unix-timestamps. Here is my attempt:

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

Starting with PHP, where "U" is the date format used to parse / output the date as unix-timestamps, when I run my attempt code, I get this RuntimeException:

Unknown character 'U' character

I assume that Gson uses SimpleDateformat under the hood, which does not define the letter "U".

I could write DateTypeAdapterand register it in GsonBuilder, but I am looking for a cleaner way to achieve this. A simple change DateFormatwould be wonderful.

+4
source share
2 answers

Creating a custom DateTypeAdapterwas a 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;
    }
}

Do not forget to register it

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,new MyDateTypeAdapter()).create();
+7
source

Timestamps are just that long, so you can use them in your POJO. Or use longto get nullif the field is missing.

class myPOJO {
    Long myDate;
}
0
source

Source: https://habr.com/ru/post/1665013/


All Articles