小编典典

如何为Gson编写自定义JSON解串器?

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"}]

我试图编写一个自定义反序列化器:

@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解串器?


阅读 216

收藏
2020-07-27

共1个答案

小编典典

@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类具有适当的构造函数。

2020-07-27