小编典典

Java-嵌套内嵌套的Gson解析

json

我必须与API进行交互,并且响应格式(根据我的阅读)似乎结构不良。我发现一个Google
网上论坛在这里回答了一个类似的问题,但是我在实现Response类来处理Gson.fromJson时遇到了麻烦。有没有我想念的例子?

{

"response":{
    "reference": 1023, 
    "data":{
        "user":{
            "id":"210",
            "firstName":"john",
            "lastName":"smith",
            "email":"pocahontas@gmail.com",
            "phone":"",
            "linkedid":{
                "id":"238"
            }
        }
    }
}

}

阅读 305

收藏
2020-07-27

共1个答案

小编典典

JSON对象{}可以由Map<String, Object>或Javabean类表示。这是一个使用Javabean的示例。

public class ResponseData {
    private Response response;
    // +getter+setter

    public static class Response {
        private int reference;
        private Data data;
        // +getters+setters
    }

    public static class Data {
        private User user;
        // +getter+setter
    }

    public static class User {
        private String id;
        private String firstName; 
        private String lastName;
        private String email;
        private String phone;
        private Linkedid linkedid;
        // +getters+setters
    }

    public static class Linkedid {
        private String id;
        // +getter+setter
    }
}

如下使用它:

ResponseData responseData = new Gson().fromJson(json, ResponseData.class);
2020-07-27