12

现在,当我想告诉 gson 如何解析日期时,我会这样做:

Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm").create();

但我也有只有日期的字段,而其他只有时间的字段,我希望两者都存储为 Date 对象。我怎样才能做到这一点?

4

3 回答 3

16

这个自定义的序列化器/反序列化器可以处理多种格式。您可以先尝试以一种格式解析,然后如果失败,则尝试使用第二种格式。这也应该处理空日期而不会爆炸。

public class GsonDateDeSerializer implements JsonDeserializer<Date> {

...

private SimpleDateFormat format1 = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
private SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");

...

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    try {
        String j = json.getAsJsonPrimitive().getAsString();
        return parseDate(j);
    } catch (ParseException e) {
        throw new JsonParseException(e.getMessage(), e);
    }
}

private Date parseDate(String dateString) throws ParseException {
    if (dateString != null && dateString.trim().length() > 0) {
        try {
            return format1.parse(dateString);
        } catch (ParseException pe) {
            return format2.parse(dateString);
        }
    } else {
        return null;
    }
}

}

希望对您有所帮助,祝您项目顺利。

于 2013-10-08T09:27:44.630 回答
5
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new GsonDateDeSerializer());
gson = builder.create();

上面的代码将应用新创建的 GsonDateDeSerializer 作为由 @reggoodwin 创建的 GSON 日期序列化器

于 2014-03-18T12:21:14.713 回答
0

为了更好地控制各个字段,最好通过注释来控制格式:

@JsonAdapter(value = MyDateTypeAdapter.class)
private Date dateField;

...使用类型适配器沿着这些线:

public class MyDateTypeAdapter extends TypeAdapter<Date> {
    @Override
    public Date read(JsonReader in) throws IOException {
        // If in.peek isn't JsonToken.NULL, parse in.nextString() () appropriately
        // and return the Date...
    }

    @Override
    public void write(JsonWriter writer, Date value) throws IOException {
        // Set writer.value appropriately from value.get() (if not null)...
    }
}
于 2017-09-21T08:47:11.347 回答