Problems with Google Gson: Unparseable date: "Apr 19, 1991"

0

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??

    
asked by anonymous 27.12.2017 / 19:27

1 answer

0

Well, I was able to resolve the implemented class in this way:

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) {
        }
        try {
            return new SimpleDateFormat(format, new Locale("pt", "BR")).parse(jsonElement.getAsString());
        } catch (ParseException e) {
        }
    }
    throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
            + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}

}

This is the solution here for anyone who has the same problem.

    
02.01.2018 / 20:08