Skip to content

Instantly share code, notes, and snippets.

@4gus71n
Created September 2, 2017 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4gus71n/56e522a073e08fc2365278460d7a9dea to your computer and use it in GitHub Desktop.
Save 4gus71n/56e522a073e08fc2365278460d7a9dea to your computer and use it in GitHub Desktop.
public class ISO8601DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
public ISO8601DateAdapter() {
}
@Override
public Date deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
if (!(json instanceof JsonPrimitive)) {
throw new JsonParseException("The date should be a string value");
}
Date date = deserializeToDate(json);
if (type == Date.class) {
return date;
} else if (type == Timestamp.class) {
return new Timestamp(date.getTime());
} else if (type == java.sql.Date.class) {
return new java.sql.Date(date.getTime());
} else {
throw new IllegalArgumentException(getClass() + " cannot deserialize to " + type);
}
}
private Date deserializeToDate(JsonElement json) {
try {
return ISO8601DateParser.parse(json.getAsString());
} catch (ParseException e) {
throw new JsonSyntaxException(json.getAsString(), e);
}
}
@Override
public JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(ISO8601DateParser.format(date));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment