配置Gson使用多种日期格式

时间:2013-10-08 08:40:04

标签: android date gson

我现在想要告诉gson如何解析我做的日期:

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

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

3 个答案:

答案 0 :(得分:12)

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

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;
    }
}

}

希望对您的项目有所帮助,祝你好运。

答案 1 :(得分:4)

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new GsonDateDeSerializer());
gson = builder.create();

上面的代码将新创建的GsonDateDeSerializer应用为由@reggoodwin创建的GSON Date序列化程序

答案 2 :(得分: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)...
    }
}