简体   繁体   English

Android Retrofit从JSON响应获取数据

[英]Android Retrofit Get Data From JSON Response

With my app I have the following JSON Response 使用我的应用程序,我有以下JSON响应

{
    "status_code": 1000,
    "data": [
        "6b456880-629a-11e9-94e5-15f45eea94be",
        1101
    ],
    "message": "Verified"
}

Im using Retrofit and my response object is 我正在使用改造,我的响应对象是

public class basicRes {


    @SerializedName("status_code")
    int status_code;
    @SerializedName("data")
    userInfo data;
    @SerializedName("message")
    String message;

    public int getStatus_code() {
        return status_code;
    }

    public userInfo getData() {
        return data;
    }

    public String getMessage() {
        return message;
    }

    public class userInfo{
        String user_id;
        int province;

        public String getUser_id() {
            return user_id;
        }

        public int getProvince() {
            return province;
        }
    } 

But I'm getting the following error 但我收到以下错误

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 29 path $.data 预期为BEGIN_OBJECT,但位于第1行第29列路径$ .data的BEGIN_ARRAY

Any help will be much appreciated 任何帮助都感激不尽

This is because the JSON response is returning array for the data key, whereas the model type being used for data is object. 这是因为JSON响应正在返回data键的数组,而用于data的模型类型是object。

The response should be in format 回应应采用以下格式

{
    "status_code": 1000,
    "data": {
        "user_id": "6b456880-629a-11e9-94e5-15f45eea94be",
        "province": 1101
    },
    "message": "Verified"
}

Your userInfo should be arraylist such as below: 您的userInfo应该是arraylist,如下所示:

public class basicRes { 公共类basicRes {

@SerializedName("status_code")
int status_code;
@SerializedName("data")
Arraylist<userInfo> data = new Arraylist<userInfo>();
@SerializedName("message")
String message;

public int getStatus_code() {
    return status_code;
}

public Arraylist<userInfo> getData() {
    return data;
}

public String getMessage() {
    return message;
}

public class userInfo{
    String user_id;
    int province;

    public String getUser_id() {
        return user_id;
    }

    public int getProvince() {
        return province;
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM