Created
December 22, 2017 12:15
-
-
Save jcbribeiro/583ff5b23e2487a1a9d533c25e76a90a to your computer and use it in GitHub Desktop.
Gson does not support deserialization of Microsoft's DateTime format out of the box. This custom JsonDeserializer is registered for the Date type. Gson will use it to deserialize for the Date type instead of its default. The same can be done for any other type, if you want to serialize/deserialize it in a custom way. More info: https://stackover…
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
| // more info: https://stackoverflow.com/a/12878774 | |
| Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date> () { | |
| public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { | |
| // example string: "/Date(1513943979489+0000)/" | |
| String s = json.getAsJsonPrimitive().getAsString(); | |
| // A plus sign (+) indicates hours ahead of GMT and a minus sign (-) indicates hours behind GMT | |
| // https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings | |
| // FIX: ignore the sign, and digits after it | |
| int gmtIndicatorIndex = s.indexOf('+') == -1 ? s.indexOf('-') : s.indexOf('+'); | |
| long l; | |
| if (gmtIndicatorIndex == -1) { | |
| l = Long.parseLong(s.substring(6, s.length() - 2)); | |
| } else { | |
| l = Long.parseLong(s.substring(6, gmtIndicatorIndex)); | |
| } | |
| Date d = new Date(l); | |
| return d; | |
| } | |
| }).create(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment