【问题标题】:Parsing json correctly using GSON and Java使用 GSON 和 Java 正确解析 json
【发布时间】:2020-06-28 19:25:56
【问题描述】:

这是我的 json 字符串,因为我想将它转换为 Java 类:

"result": {
    "id": "39559",
    "first_name": "John",
    "last_name": "Who",
    "gender": "male",
    "dob": null,
    "email": "john.who@roberts.com",
    "phone": null,
    "website": null,
    "address": null,
    "status": "active",
    "_links": {
        "self": {
            "href": "https://gorest.co.in/public-api/users/39559"
        },
        "edit": {
            "href": "https://gorest.co.in/public-api/users/39559"
        },
        "avatar": {
            "href": null
        }
    }
}

这是我的课(我删除了 getter 和 toString):

public class Result {
    String id, user_id, title, first_name, last_name, gender, dob, email, phone,
            website, address, status, _links, album_id, url, thumbnail, post_id, name, body;
}

我想知道我该如何代表

"_links": {
    "self": {
        "href": "https://gorest.co.in/public-api/users/39559"
    },
    "edit": {
        "href": "https://gorest.co.in/public-api/users/39559"
    },
    "avatar": {
        "href": null
    }
}

如何在我的 Result 类中表示缺失的部分?

【问题讨论】:

    标签: java string gson


    【解决方案1】:

    _links 似乎是一个 JSON 对象,具有 selfeditavatar 属性。这些属性中的每一个也是 JSON 对象,都具有属性 href。 → 你需要这三个类来表示这些对象:

    public class Result {
        String id, user_id, title, first_name, last_name, gender;
        String dob, email, phone, website, address, status;
        String album_id, url, thumbnail, post_id, name, body;
        Links _links;
    }
    
    public class Links {
        Link self, edit, avatar;
    }
    
    public class Link {
        String href;
    }
    

    【讨论】:

      【解决方案2】:

      您需要将链接创建为带有字段的对象

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-14
        • 1970-01-01
        • 2011-04-26
        相关资源
        最近更新 更多