简体   繁体   中英

Android Retrofit Get Data From JSON Response

With my app I have the following JSON Response

{
    "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

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.

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:

public class 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;
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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