Retrofit 2如何从嵌套的json对象获取响应(android)

时间:2016-02-12 10:43:17

标签: android json retrofit retrofit2

这是我的第一个json响应,我得到了令牌

{
"token": "I0ZmEifQ.CdbGWjkIYnuO29uJokCIGn8kXFbLbVp3gnlsEszagno"
}

pojo class

public class TokenReceiver {
    private String token; 

    public String getToken() {
        return token;
    }
}

以上工作正常,但如何得到以下的回复

{
  "user": {
    "id": 1,
    "first_name": "Super",
    "last_name": "Admin",
    "email": "abc@sad.sdf",
    "mobile_no": 2147483647,
    "created_at": "2016-01-21 00:00:00",
    "updated_at": "2016-01-21 00:00:00",
    "user_role_id": 1
  }
}

状态代码为200(OK) 但数据没有附加到pojo

public class User {

    @SerializedName("id")
    @Expose
    private int id;

    @SerializedName("first_name")
    @Expose
    private String first_name;

    @SerializedName("last_name")
    @Expose
    private String last_name;

    @SerializedName("email")
    @Expose
    private String email;

    @SerializedName("mobile_no")
    @Expose
    private String mobile_no;

    @SerializedName("created_at")
    @Expose
    private String created_at;

    @SerializedName("updated_at")
    @Expose
    private String updated_at;

    @SerializedName("user_role_id")
    @Expose
    private int user_role_id;
}

提前致谢

2 个答案:

答案 0 :(得分:7)

public class Response{
    @SerializedName("user")
    @Expose
    private User user;
  }
public class User{

@SerializedName("id")
@Expose
private int id;

@SerializedName("first_name")
@Expose
private String first_name;

@SerializedName("last_name")
@Expose
private String last_name;

@SerializedName("email")
@Expose
private String email;

@SerializedName("mobile_no")
@Expose
private String mobile_no;

@SerializedName("created_at")
@Expose
private String created_at;

@SerializedName("updated_at")
@Expose
private String updated_at;

@SerializedName("user_role_id")
@Expose
private int user_role_id;
}

可以通过下面提到的内部响应来访问。

response.getUser().getId();

答案 1 :(得分:1)

Public class classname{

public User user;
 class User{

@SerializedName("id")
@Expose
private int id;

@SerializedName("first_name")
@Expose
private String first_name;

@SerializedName("last_name")
@Expose
private String last_name;

@SerializedName("email")
@Expose
private String email;

@SerializedName("mobile_no")
@Expose
private String mobile_no;

@SerializedName("created_at")
@Expose
private String created_at;

@SerializedName("updated_at")
@Expose
private String updated_at;

@SerializedName("user_role_id")
@Expose
private int user_role_id;
}
}

以上代码适合您