Answer the question
In order to leave comments, you need to log in
How to set 2 format types for GSON?
Good afternoon.
2 types of date come from the server:
1)"yyyy-MM-dd"
2)"yyyy-MM-dd HH:mm:ss".
How to set the date format for GSON, so that it would parse according to the 2nd format if there are hours and minutes, and if not, then parse by 1 ?
private static final Gson GSON = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.setDateFormat("yyyy-MM-dd")
.create();
Answer the question
In order to leave comments, you need to log in
I found the answer in 2 seconds
stackoverflow.com/questions/15563155/gson-to-json-...
new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer());
private static final String[] DATE_FORMATS = new String[] {
"MMM dd, yyyy HH:mm:ss",
"MMM dd, yyyy"
};
private class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question