简体   繁体   中英

deserialize two different date formats with 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM