Work with Google's Gson to persist and retrieve Java Objects. I use this code to create and format Gson, in order to prepapake it to receive certain date formats, which comes from forms and the database.
Gson g = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).create();
This is the DateDeserializer class, which gets a Gson and parses with Dates formats, avoiding the vast majority of errors.
public class DateDeserializer implements JsonDeserializer<Date> {
private static final String[] DATE_FORMATS = new String[]{
"MMM dd, yyyy HH:mm:ss",
"MMM dd, yyyy",
"dd/MM/yyyy",
"mmm dd, yyyy",
"yyyy/MM/dd",
"yyyy-MM-dd",
"dd-MM-yyyy"
};
@Override
public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jdc) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.ROOT).parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
The problem is in the format that I put in the title: "Apr 19, 1991" . It always generates this error: Unparseable date , although I have already put several formats inside the Deserialization class. Has anyone experienced this or do you know how to fix it??