Created
September 3, 2017 15:27
-
-
Save 4gus71n/972abf0eccd098c18129b768a9966952 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
import com.google.gson.JsonDeserializationContext; | |
import com.google.gson.JsonDeserializer; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonParseException; | |
import com.google.gson.JsonPrimitive; | |
import com.google.gson.JsonSerializationContext; | |
import com.google.gson.JsonSerializer; | |
import com.google.gson.JsonSyntaxException; | |
import net.misove.mypvrcommon.serialization.ISO8601DateParser; | |
import java.lang.reflect.Type; | |
import java.sql.Time; | |
import java.text.ParseException; | |
import java.util.Date; | |
import java.util.TimeZone; | |
public class ISO8601TimeAdapter implements JsonSerializer<Time>, JsonDeserializer<Time> { | |
public ISO8601TimeAdapter() { | |
} | |
@Override | |
public Time 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 == Time.class) { | |
return new Time(date.getTime()); | |
} | |
throw new IllegalArgumentException(getClass() + " cannot deserialize to " + type); | |
} | |
private Date deserializeToDate(JsonElement json) { | |
try { | |
return ISO8601DateParser.parse(json.getAsString(), TimeZone.getDefault()); | |
} catch (ParseException e) { | |
throw new JsonSyntaxException(json.getAsString(), e); | |
} | |
} | |
@Override | |
public JsonElement serialize(Time time, Type type, JsonSerializationContext jsonSerializationContext) { | |
return new JsonPrimitive(ISO8601DateParser.format(time)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment