Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize two different date formats with GSON

Tags:

java

json

gson

Im consuming a clients JSON API using googles GSON lib to handle serialisation/deserialization. This is proving to be problematic as within the API's json entities there are a number of date formats scattered about the API.

Some examples of this are as follows...

"2014-02-09"

"15/10/1976"

"2014-02-09T07:32:41+00:00"

I have no control over the API as it developerd by the client and is already being consumed by other parties. It seems that I can setup GSON to work with a single date format but I cant get it parse the dates on a per field basis.

I would have expected GOSN to provide an annotation for this but I cant seem to find one. Any ideas on ho to set this up anyone?

like image 547
carrot_programmer_3 Avatar asked Feb 09 '14 18:02

carrot_programmer_3


1 Answers

Since you have multiple Date fields in your POJO, and the incomming JSON has those dates in different formats, you'd need to write a custom deserializer for Date that can handle those formats.

class DateDeserializer implements JsonDeserializer<Date>
{
    @Override
    public Date deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
    {
        String myDate = je.getAsString();
        // inspect string using regexes
        // convert string to Date        
        // return Date object
    }

}

You can the register this as a type adapter when creating your Gson instance:

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

You can, of course, also just write a custom deserializer for your POJO and populate everything yourself from the parse tree.

Another option would be to simply set them as a String in your POJO, then make the getters for each field convert them to Date.

Outside of that, if you're not completely attached to using Gson, the Jackson JSON parser (by default) uses your POJO's setters during deserializtion which would give you the explicit control over setting each field.

like image 196
Brian Roach Avatar answered Sep 20 '22 20:09

Brian Roach