Last active
June 7, 2019 00:56
-
-
Save bbirec/5748489 to your computer and use it in GitHub Desktop.
ISO8601 Adapter for Gson.
This file contains hidden or 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
package com.bbirec.dabang.common; | |
import com.google.gson.*; | |
import java.lang.reflect.Type; | |
import java.sql.Timestamp; | |
import java.text.DateFormat; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import java.util.Locale; | |
import java.util.TimeZone; | |
final class ISODateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> { | |
private final DateFormat iso8601Format; | |
ISODateAdapter() { | |
this.iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); | |
this.iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); | |
} | |
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { | |
String dateFormatAsString = iso8601Format.format(src); | |
return new JsonPrimitive(dateFormatAsString); | |
} | |
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) | |
throws JsonParseException { | |
if (!(json instanceof JsonPrimitive)) { | |
throw new JsonParseException("The date should be a string value"); | |
} | |
Date date = deserializeToDate(json); | |
if (typeOfT == Date.class) { | |
return date; | |
} else if (typeOfT == Timestamp.class) { | |
return new Timestamp(date.getTime()); | |
} else if (typeOfT == java.sql.Date.class) { | |
return new java.sql.Date(date.getTime()); | |
} else { | |
throw new IllegalArgumentException(getClass() + " cannot deserialize to " + typeOfT); | |
} | |
} | |
private Date deserializeToDate(JsonElement json) { | |
try { | |
return iso8601Format.parse(json.getAsString()); | |
} catch (ParseException e) { | |
throw new JsonSyntaxException(json.getAsString(), e); | |
} | |
} | |
} |
how do I use it ?
Where do I configure it ?
Thanks
@leonardo2204, just use it when you creating your Gson instance, for example
private static Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new ISODateAdapter())
.create();
This is really useful. Thanks!
제 시간을 아껴주셨습니다. 감사합니다.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning: java.text.SimpleDateFormat's parse() is not thread safe