Created
September 2, 2017 04:41
-
-
Save 4gus71n/56e522a073e08fc2365278460d7a9dea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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