Deserialize two different date formats using GSON

Im using the client JSON API using googles GSON lib to handle serialization / deserialization. This turns out to be problematic, as there are several date formats scattered across the API inside json API objects.

Here are some examples of this:

"2014-02-09"

"15/10/1976"

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

I have no control over the API, as it was created by the client and is already used by other parties. It seems that I can configure GSON to work with one date format, but I can not parse the dates on the field.

I would expect GOSN to provide an annotation for this, but I cannot find it. Any ideas on setting someone up?

+6
source share
1 answer

Since your POJO has several Date fields, and incoming JSON have these dates in different formats, you need to write your own deserializer for Date that can handle these 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 register this as a type adapter when creating a Gson instance:

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

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

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

In addition, if you are not completely attached to using Gson, the Jackson JSON parser (by default) uses your POJO setters during deserialization, which will give you explicit control over the setting of each field.

+6
source

All Articles