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?
I'd take a slightly different approach as follows, so as to minimize "manual" parsing in my code, as unnecessarily doing otherwise somewhat defeats the purpose of why I'd use an API like Gson in the first place.
(This assumes that "date_date" should be "update_date", in the original question.)
I'm assuming User class has the appropriate constructor.