Saturday, February 9, 2013

Gson and Date Formatting

Gson is a really cool tool to quickly convert regular POJOs to json strings and back. It's super simple to setup and even easier to use:

 final Gson gson = new GsonBuilder().create();  
 final String jsonString = gson.toJson(myPojo);  
 final Pojo myPojo = gson.fromJson(jsonString, Class);  

However, by default it appears that Gson uses a fairly simple date formatter that seems to be locale specific. In most cases, this should be alright unless you need to parse a more fine grained date, such as something like "2013/02/09 15:07:50 +0000". When using gson to parse a date like it does fail, and you get exceptions:

 Caused by: java.text.ParseException: Unparseable date: "2013/02/09 15:07:50 +0000"  

Obviously this is not wanted and knowing that this is a valid date makes it even stranger that gson couldn't handle it. The answer? You can override the date parsing adapter that gson uses by default with your own version. For my example, I had to override it with the following:

final GsonBuilder builder = new GsonBuilder();  
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {  
    // Year in 4, month in 2, day in 2, hour in 24, minutes in hour, seconds in minute, timezone in 4  
    final DateFormat df = new SimpleDateFormat("yyyy/MM/dd kk:mm:ss Z");  
    public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {  
        try {  
            return df.parse(json.getAsString());  
        } catch (final java.text.ParseException e) {  
            return null;  
return builder.create();  

So, this is a really simple yet powerful way to use gson even when you have difficult dates that need to parsed.

No comments:

Post a Comment