用两个DateFormat将Gson转换为json

时间:2013-03-22 05:09:52

标签: java gson

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

当我使用以下内容转换JSON时,它很好:

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

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

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

gson有没有办法为其Json转换处理两个不同的DateFormat?

3 个答案:

答案 0 :(得分:65)

我遇到了同样的问题。这是我通过自定义反序列化的解决方案:

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

答案 1 :(得分:8)

虽然答案已被接受,但我想分享一个类似但更具可扩展性的解决方案。您可以找到gist here

DateDeserializer.java

public class DateDeserializer<T extends Date> implements JsonDeserializer<T> {

    private static final String TAG = DateDeserializer.class.getSimpleName();

    private final SimpleDateFormat mSimpleDateFormat;
    private final Class<T> mClazz;

    public DateDeserializer(SimpleDateFormat simpleDateFormat, Class<T> clazz) {
        mSimpleDateFormat = simpleDateFormat;
        mClazz = clazz;
    }

    @Override
    public T deserialize(JsonElement element, Type arg1, JsonDeserializationContext context) throws JsonParseException {
        String dateString = element.getAsString();
        try {
            T date = mClazz.newInstance();
            date.setTime(mSimpleDateFormat.parse(dateString).getTime());
            return date;
        } catch (InstantiationException e) {
            throw new JsonParseException(e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new JsonParseException(e.getMessage(), e);
        } catch (ParseException e) {
            throw new JsonParseException(e.getMessage(), e);
        }
    }
}

然后将不同的格式注册为......

sGson = new GsonBuilder()
                    .registerTypeAdapter(Event.EventDateTime.class,
                            new DateDeserializer<Event.EventDateTime>(
                                    Event.EventDateTime.DATE_FORMAT, Event.EventDateTime.class))
                    .registerTypeAdapter(Event.StartEndDateTime.class,
                            new DateDeserializer<Event.StartEndDateTime>(
                                    Event.StartEndDateTime.DATE_FORMAT, Event.StartEndDateTime.class))
                    .registerTypeAdapter(Event.SimpleDate.class,
                            new DateDeserializer<Event.SimpleDate>(
                                    Event.SimpleDate.DATE_FORMAT, Event.SimpleDate.class))
                    .create();

然后将每种格式映射到一个类......

public class Event {

    @SerializedName("created")
    private EventDateTime mCreated;

    //@SerializedName("updated")
    private EventDateTime mUpdated;

    ...

    @SerializedName("start")
    private ConditionalDateTime mStart;

    @SerializedName("end")
    private ConditionalDateTime mEnd;

    public static class ConditionalDateTime {
        @SerializedName("dateTime")
        private StartEndDateTime mDateTime;

        @SerializedName("date")
        private SimpleDate mDate;

        public SimpleDate getDate() {
            return mDate;
        }

        public StartEndDateTime getDateTime() {
            return mDateTime;
        }

        /**
         * If it is an all day event then only date is populated (not DateTime)
         * @return
         */
        public boolean isAllDayEvent() {
            return mDate != null;
        }
    }

    public static class EventDateTime extends Date {
        public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    }

    public static class StartEndDateTime extends Date {
        public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
    }

    public static class SimpleDate extends java.util.Date {
        public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    }
}

答案 2 :(得分:2)

自定义反序列化是必要的。一个不错的解决方案是使用Apache Commons DateUtil,它可以同时处理多种日期格式。此外,JodaTime API可能具有类似的功能。