0
I work with Google Gson to persist and recover Java objects. I use this code to create and format Gson, with the aim of preplanning it to receive certain date formats, which come from forms and the database.
Gson g = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).create();
This is the Datedeserializer class, which receives a Gson and parses with Date 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 I put in the title: "Apr 19, 1991". Always generates this error: Unparseable date, however much I have already put several formats within the Deserialization class. Someone has already gone through this or knows how to solve..?