How do I write a custom JSON deserializer for Gson?
deserialization, gson, java, json
Solution
@Override
public User deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jobject = json.getAsJsonObject();
return new User(
jobject.get("id").getAsInt(),
jobject.get("name").getAsString(),
new Timestamp(jobject.get("update_date").getAsLong()));
}
I'm assuming User class has the appropriate constructor.
Problem
I have a Java class, User: ``` public class User { int id; String name; Timestamp updateDate; } ``` And I receive a JSON list containing user objects from a webservice: ``` [{"id":1,"name":"Jonas","update_date":"1300962900226"}, {"id":5,"name":"Test","date_date":"1304782298024"}] ``` I have tried to write a custom deserializer: ``` @Override public User deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return new User( json.getAsJsonPrimitive().getAsInt(), json.getAsString(), json.getAsInt(), (Timestamp)context.deserialize(json.getAsJsonPrimitive(), Timestamp.class)); } ``` But my deserializer doesn't work. How can I write a custom JSON deserializer for Gson?