Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Gson to use several Date formats

Tags:

date

android

gson

I now that when I want to tell gson how to parse dates I do:

Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm").create();

But I have also fields with only the date, and others with only the time, and I want both to be stored as Date objects. How can I do this?

like image 298
apinho Avatar asked Oct 08 '13 08:10

apinho


2 Answers

This custom serializer/deserializer can handle multiple formats. You could first try parsing in one format, then if that fails then try with a second format. This should also handles null dates without blowing up as well.

public class GsonDateDeSerializer implements JsonDeserializer<Date> {

...

private SimpleDateFormat format1 = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
private SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");

...

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    try {
        String j = json.getAsJsonPrimitive().getAsString();
        return parseDate(j);
    } catch (ParseException e) {
        throw new JsonParseException(e.getMessage(), e);
    }
}

private Date parseDate(String dateString) throws ParseException {
    if (dateString != null && dateString.trim().length() > 0) {
        try {
            return format1.parse(dateString);
        } catch (ParseException pe) {
            return format2.parse(dateString);
        }
    } else {
        return null;
    }
}

}

Hope that helps, good luck with your project.

like image 81
reggoodwin Avatar answered Sep 20 '22 14:09

reggoodwin


GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new GsonDateDeSerializer());
gson = builder.create();

Above code will apply the new created GsonDateDeSerializer as GSON Date serializer which created by @reggoodwin

like image 24
Songlin Avatar answered Sep 23 '22 14:09

Songlin