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

Asked

Viewed 180 times

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

1 answer

0


Well, I managed to get the class implemented that 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));
}

}

The solution is here for those who have the same problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.