Gson时间反序列化

Gson time deserilization

我有一个 JSON 字符串,我想使用 Gson 反序列化 - {"Id":3,"Title":"Roskilde","Description":"Famous Danske festival","StartingTime":"2016-06-12T00:00:00","Duration":"02:02:00"} 尝试反序列化 Duration 字段时出现的错误:

Unparseable date: "02:02:00"

反序列化器(我的想法是添加两种可能的日期反序列化格式):

Gson gSon=  new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).create();


private static final String[] DATE_FORMATS = new String[] {
        "yyyy-MM-dd'T'HH:mm:ss",
        "HH:mm:ss"
};


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

和我的事件 Class(如您所见,"Duration" 不是日期类型 - 它是时间类型 - 我应该怎么做才能使反序列化器将 Duration 读取为时间类型日期?

    private int Id;
private String Title;
private String Description;
private Date StartingTime;
private Time Duration;
public Event(int id, String title,String description, String place, Date startingTime, Time duration)
{
    this.Id = id;
    this.Description = description;
    this.Title = title;
    this.StartingTime = startingTime;
    this.Duration = duration;
}

您应该为日期和时间注册一个反序列化器。像这样:

try{
    // Convert JSON-string to a List of Event objects
    Type listType = new TypeToken<ArrayList<Event>>(){}.getType();
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            try{
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
                return df.parse(json.getAsString());
            }
            catch(ParseException ex){
                return null;
            }
    });
    gsonBuilder.RegisterTypeAdapter(Time.class, new JsonDeserializer<Time>(){
        @Override
        public Time deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                try{
                    DateFormat df = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
                    return df.parse(json.getAsString());
                }
                catch(ParseException ex){}
            }
            return null;
        }
    });
    Gson eventGson = gsonBuilder.create();
    events = dateGson.fromJson(json, listType);
}
catch(JsonParseException ex){
    ex.printStackTrace();
}

PS:这段代码未经测试,因为我没有太多时间。但我想你明白了。您只需要两个 JsonDeserializer,一个用于时间,一个用于日期。

为时间反序列化添加另一个 class - 确保将 return 值转换为 "Time"。 (另见:cast a String to sql time

    private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
    private static final String TIME_FORMAT = "HH:mm:ss";

    private class DateDeserializer implements JsonDeserializer<Date> {

        @Override
        public Date deserialize(JsonElement jsonElement, Type typeOF,
                                JsonDeserializationContext context) throws JsonParseException {
                try {
                    return new SimpleDateFormat(DATE_FORMAT, Locale.US).parse(jsonElement.getAsString());
                } catch (ParseException e) {
                }

            throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
                    + "\". Supported formats: " + DATE_FORMAT);
        }
    }

    private class TimeDeserializer implements JsonDeserializer<Time> {

        @Override
        public Time deserialize(JsonElement jsonElement, Type typeOF,
                                JsonDeserializationContext context) throws JsonParseException {
                try {

                    String s = jsonElement.getAsString();
                    SimpleDateFormat sdf = new SimpleDateFormat(TIME_FORMAT, Locale.US);
                    sdf.parse(s);
                    long ms = sdf.parse(s).getTime();
                    Time t = new Time(ms);
                    return t;
                } catch (ParseException e) {
                }
            throw new JsonParseException("Unparseable time: \"" + jsonElement.getAsString()
                    + "\". Supported formats: " + TIME_FORMAT);
        }
    }

同时注册 classes:

    GsonBuilder gSonBuilder=  new GsonBuilder();
    gSonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
    gSonBuilder.registerTypeAdapter(Time.class, new TimeDeserializer());
    Gson gSon = gSonBuilder.create();