Skip to content
Advertisement

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:

JavaScript

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.

Advertisement

Answer

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

UnixTimestampAdapter

JavaScript

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:

JavaScript

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

JavaScript
Advertisement