Java如何为Gson编写自定义JSON解串器?
我有一个Java类,用户:
public class User{
int id;
String name;
Timestamp updateDate;
}
我收到一个包含来自Web服务的用户对象的JSON列表:
[{"id":1,"name":"Jonas","update_date":"1300962900226"},{"id":5,"name":"Test","date_date":"1304782298024"}]
我试图编写一个自定义反序列化器:
@Overridepublic 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解串器?
回答:
@Overridepublic 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()));
}
以上是 Java如何为Gson编写自定义JSON解串器? 的全部内容, 来源链接: utcz.com/qa/404553.html