如何为 Gson 编写自定义 JSON 反序列化器?
问题描述:
我有一个 Java 类,用户:
I have a Java class, User:
public class User
{
int id;
String name;
Timestamp updateDate;
}
我收到一个包含来自网络服务的用户对象的 JSON 列表:
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));
}
但是我的解串器不起作用.如何为 Gson 编写自定义 JSON 反序列化器?
But my deserializer doesn't work. How can I write a custom JSON deserializer for Gson?
答
@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()));
}
我假设 User 类具有适当的构造函数.
I'm assuming User class has the appropriate constructor.