Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson dateformat to serialize/deserialize unix-timestamps

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 serialize/deserialize date as unix-timestamps, when running my attempt code, I am a RuntimeException:

Unknown pattern character 'U'

I am assuming that Gson uses SimpleDateformat under the hood which doesn't define the letter "U".

I could implement a custom DateTypeAdapter but I am looking for a cleaner way to achieve that. Simply changing the DateFormat would be great.

like image 685
Anis LOUNIS Avatar asked Dec 27 '16 15:12

Anis LOUNIS


People also ask

What is the default date format of default Gson localdateserializer?

1. Custom GSON LocalDateSerializer Note that we are formatting default local date "2018-10-26" to "27-Oct-2018". 2. Custom GSON LocalDateTimeSerializer

How to deserialize JSON with extra Unknown Fields in Gson?

Deserialize JSON With Extra Unknown Fields to Object Next – let's deserialize some complex json that contains additional, unknown fields: As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

How to convert JSON timestamps to time in go?

The best solution would be that during the the unmarshal of the JSON, we can convert the timestamps directly into a time.Time instance. There is (as usual) a neat way of handling this in Go. The trick is to define a custom type and implement MarshalJSON and UnmarshalJSON.

What is a Unix time stamp?

The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the unix time stamp is merely the number of seconds between a particular


1 Answers

Creating a custom TypeAdapter (UnixTimestampAdapter) was the way to go.

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.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        return new Date(in.nextLong() * 1000);
    }

}

Now, you have to options (depending on your use case):

1 - If you want apply this serialization on all your date fields then register UnixTimestampAdapter upon creating your Gson instance:

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

2 - Or annotate your date fields with @JsonAdapter (as suggested by @Marcono1234) if you want it applied only to some specific fields.

class Person {
    @JsonAdapter(UnixTimestampAdapter.class)
    private Date birthday;
}
like image 154
Anis LOUNIS Avatar answered Oct 30 '22 08:10

Anis LOUNIS