Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2 how to get the response from nested json objects (android)

this is my first json response and i got the token

{
"token": "I0ZmEifQ.CdbGWjkIYnuO29uJokCIGn8kXFbLbVp3gnlsEszagno"
}

pojo class

public class TokenReceiver {
    private String token; 

    public String getToken() {
        return token;
    }
}

the above worked fine but how to get the response for below

{
  "user": {
    "id": 1,
    "first_name": "Super",
    "last_name": "Admin",
    "email": "[email protected]",
    "mobile_no": 2147483647,
    "created_at": "2016-01-21 00:00:00",
    "updated_at": "2016-01-21 00:00:00",
    "user_role_id": 1
  }
}

the status code is 200 (OK) but the data is not getting attached to the 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;
}

thanks in advance

like image 921
Gowsik K C Avatar asked Feb 12 '16 10:02

Gowsik K C


2 Answers

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

Inner Response can be accessed by below mentioned.

response.getUser().getId();
like image 106
learner Avatar answered Sep 28 '22 02:09

learner


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

Above code will work for you

like image 24
MathankumarK Avatar answered Sep 28 '22 02:09

MathankumarK