我有一个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"}]

我try 编写一个自定义反序列化程序:

@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?

推荐答案

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

Json相关问答推荐

输入请求中不存在null的条件抖动

最新版本的Deneb在数据溢出时不支持滚动

Ansible - 将文件内容添加到字典中

如何将具有相同 struct 的多个JSON文件中的对象数组合并成一个数组?

基于JQ中另一个对象的值 Select 对象

如何在JQ中展平多维数组

如何编写 jolt 规范以将不同的对象转换为数组

将 JSON 文件放在哪里以在 Angular 8 应用程序中加载静态 JSON 数据?

流编写器未写入 webapi 中的 JSON 文件

JQuery,使用 GET 方法发送 JSON 对象

JSON.NET 中特定对象的自定义转换

如何使用 Serde 使用顶级数组反序列化 JSON?

如何使用 CORS 实现 JavaScript Google Places API 请求

使用 boost 属性树读取 int 数组

如何从 mysql 数据库构建 JSON 数组

JSON 到 JSON 转换器

如何在spark 上将json字符串转换为数据帧

ASP.NET Web API JSON 输出中没有时间的日期

设置对象不是 JSON 可序列化的

在 iPhone 上解析 JSON 日期