A
A
Alexander Popov2015-09-24 10:57:03
Android
Alexander Popov, 2015-09-24 10:57:03

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();

if you do it like this, then it will always parse without time, and if you swap it, it will crash with an error if there is no time.
ps Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Emin, 2015-09-24
@Chuffey

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 question

Ask a Question

731 491 924 answers to any question