在gson/retrofit中,是否有内置的方法来处理不同格式的日期?

3
我目前使用的API以"yyyy-MM-dd"和典型的ISO8601格式"2012-06-08T12:27:29.000-04:00"返回日期(为了这个问题,日期和日期时间是相同的)。
如何“干净地”设置GSON来处理此类日期?或者我的最佳方法是将日期视为字符串,并在模型对象中使用一些自定义getter输出特定格式所需的内容?
我目前正在执行以下操作,但是每当我看到一个“yyyy-MM-dd”字段时,解析就会失败。
return new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
    .create();

如果有适用于Android + Retrofit的解决方案,请使用它。以下是需要翻译的内容:


编辑:根据下面的建议,我创建了一个自定义TypeAdapter。可以在此处查看我的完整解决方案(作为gist):https://gist.github.com/loeschg/2967da6c2029ca215258


你可能需要为日期注册一个自定义的TypeAdapter,它将尝试各种格式。 - njzk2
1个回答

3
我会这样做:(未经测试):
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();

一个自定义类型适配器,尝试多种格式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接