Does gson / retrofit have a built in way of handling dates in different formats?

In the api I am using the return dates (for this question, the dates and dates are the same) in the form "yyyy-MM-dd" and also in the ISO8601 standard format "2012-06-08T12: 27: 29.000-04: 00"

How did you "cleanly" configure GSON to handle this? Or would my best approach be to treat dates as strings and output in the specific form needed using some custom getter in my model objects?

I am currently doing the following, but the parsing fails when I see the "yyyy-MM-dd" field.

return new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
    .create();

      

I end up using this in the Android + Retrofit context if there are solutions available via this brochure.


Edit . In the suggestion below, I've created a custom TypeAdapter. My complete solution can be seen here (here): https://gist.github.com/loeschg/2967da6c2029ca215258 .

+3


source to share


1 answer


I love so much: (untested though):

SimpleDateFormat[] formats = new SimpleDateFormat[] {
    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"),
    // Others formats go here
};

// ...

return new GsonBuilder()
    .registerTypeAdapter(Date.class, new TypeAdapter<Date>() {

        @Override
        public Date read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String dateAsString = reader.nextString();
            for (SimpleDateFormat format : formats) {
                try {
                    return format.parse(dateAsString);
                } catch (ParseException e) {}  // Ignore that, try next format
            }
            // No matching format found!
            return null;
        }
    })
    .create();

      



A custom type adapter that tries to use multiple formats.

+3


source







All Articles