AFLAH ALI
AFLAH ALI

Reputation: 451

How to use retrofit with response format varies according to a parameter?

I have a login api where response format varies according to type of user logging in.

Json structure with "type" = 4

{
    "type": 4,
    "user": {
        "coord_id": 5,
        "coord_login_id": 4,
        "coord_name": "Randall Pfannerstill",
    }
}

Json Format with "type" = 2

{
    "type": 2,
    "user": {
        "stud_id": 1,
        "stud_reference_id": "3",
    }
} 

im using this model class for handling "type" 2

public class LoginResponse {
    @SerializedName("type")
    public int type;
    @SerializedName("user")
    public User user;

    public class User {
        @SerializedName("stud_id")
        public int stud_id;
        @SerializedName("stud_reference_id")
        public String stud_reference_id;

    }

How can handle the case with "type" = 4 with same class (or How should i write a different model class)

Upvotes: 2

Views: 124

Answers (2)

BiRjU
BiRjU

Reputation: 753

maybe you can try this

public class LoginResponse {
@SerializedName("type")
public int type;
@SerializedName("user")
public User user;

public class User {
    @SerializedName("stud_id")
    public int stud_id;
    @SerializedName("stud_reference_id")
    public String stud_reference_id;


    @SerializedName("coord_id");
    public int coord_id;
    @SerializedName("coord_login_id");
    public int coord_login_id;
    @SerializedName("coord_name")
    public String coord_name;

}
}

if data found that is store in variable ...otherwise that field store null data....you need to always check that data is null or not means if stud_id found that is store...and coord_id is null...else if crood_id is found that time stud_id is null

Upvotes: 2

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

Since your JSONs have different key names, I suggest you to use the Map instead:

public class YourPojo {
    private int type;
    private Map<String, String> user;
}

Base on your type, you should know which User you got from response

Upvotes: 2

Related Questions