I have a JSON string that I want to use deserilizie with using Gson - The {"Id":3,"Title":"Roskilde","Description":"Famous Danske festival","StartingTime":"2016-06-12T00:00:00","Duration":"02:02:00"}
error I get when I try to desert a Duration field:
Unbeatable Date: "02:02:00"
Deserilizer (my idea was to add two possible date deserialization formats):
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));
}
}
and my event class (as you can see, "Duration" does not apply to type date - it is type "Time" - what should I do to make deserilizer read Duration as type time not date?
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;
}
Tomek source
share