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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With