Gson使用两个DateFormat进行json转换 [英] Gson to json conversion with two DateFormat

查看:326
本文介绍了Gson使用两个DateFormat进行json转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器JSON正在返回两种不同类型的DateFormat。
MMM dd,yyyy和MMM dd,yyyy HH:mm:ss

My server JSON is returning with two different type of DateFormat. "MMM dd, yyyy" and "MMM dd, yyyy HH:mm:ss"

当我使用以下代码转换JSON时,它很好:

When I convert the JSON with the following it is fine:

Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy").create();

但是,当我想要详细日期格式并将其更改为此时,它会引发异常com.google。 gson.JsonSyntaxException:2013年3月21日

But when I want the detailed date format and changed it to this, it throws exception com.google.gson.JsonSyntaxException: Mar 21, 2013

Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy HH:mm:ss").create();

有没有一种方法可以让gson处理两个不同的DateFormat进行Json转换?

Is there a way for gson to handle two different DateFormat for its Json conversion?

推荐答案

我面临同样的问题。这里是我通过自定义反序列化的解决方案:

I was facing the same issue. Here is my solution via custom deserialization:

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

这篇关于Gson使用两个DateFormat进行json转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆