Custom JSON Deserializer using Gson
suggest changeImagine every date in every response uses a custom format, for instance /Date(1465935152)/, and you want one rule that deserializes those values to Java Date instances. Implement a custom JSON deserializer. The number in this sample is Unix seconds. Date expects milliseconds.
Example of json:
{
"id": 1,
"created_on": "/Date(1465935152)/",
"updated_on": "/Date(1465968945)/",
"name": "Oleksandr"
}
Suppose we have this class below:
class User {
@SerializedName("id")
long id;
@SerializedName("created_on")
Date createdOn;
@SerializedName("updated_on")
Date updatedOn;
@SerializedName("name")
String name;
}
Custom deserializer:
class DateDeSerializer implements JsonDeserializer<Date> {
private static final String DATE_PREFIX = "/Date(";
private static final String DATE_SUFFIX = ")/";
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String dateString = json.getAsString();
if (dateString.startsWith(DATE_PREFIX) && dateString.endsWith(DATE_SUFFIX)) {
dateString = dateString.substring(DATE_PREFIX.length(), dateString.length() - DATE_SUFFIX.length());
} else {
throw new JsonParseException("Wrong date format: " + dateString);
}
return new Date(Long.parseLong(dateString) * 1000L);
}
}
And the usage:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeSerializer())
.create();
String json = "....";
User user = gson.fromJson(json, User.class);
Serialize and deserialize Jackson JSON strings with Date types
This also applies to the case where you want to make Gson Date conversion compatible with Jackson, for example.
Jackson usually serializes Date to “milliseconds since epoch” whereas Gson uses a readable format like Aug 31, 2016 10:26:17 to represent Date. This leads to JsonSyntaxExceptions in Gson when you try to deserialize a Jackson format Date.
To circumvent this, you can add a custom serializer and a custom deserializer:
A second registerTypeAdapter call for the same class replaces the first, so one object has to serialize and deserialize:
class DateEpochAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return src == null ? null : new JsonPrimitive(src.getTime());
}
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return json == null ? null : new Date(json.getAsLong());
}
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateEpochAdapter())
.create();