Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrofit JSON to POJO

I am new in android, and I'm usig retrofit.

The problem is that I can't obtain my POJO from request.

my request is:

@FormUrlEncoded
@POST("/index.php")
void login(@Field("io") String command,
           @Field("lu") String userName,
           @Field("lp") String password,
           @Field("lm") String imei,
           @Field("l") int language,
           RestCallback<ModelLoginResponse> callback);

server JSON response is:

  {
    "tk": "thdoz4hwer32",
    "pn": "1",
    "lc": {
        "1": "Opel Combo",
        "3": "VW Crafter",
        "7": "Opel Vivaro"
    },
    "stg": {
        "rs": "30",
        "sml": "http://exemple.mob.ru",
        "ssl": "index.php"
    }
}

where 1,3,7 are different every time

and my POJO class:

 @Parcel
    public class ModelLoginResponse {

    @SerializedName("pn")
    private String personalNumber;

    @SerializedName("tk")
    private String token;

    //    ?????? for "lc" and "stg" 

    public void ModelResponse(String personalNumber, String token){
        this.personalNumber = personalNumber;
        this.token = token;
    }

    public String getPersonalNumber() {
        return personalNumber;
    }

    public void setPersonalNumber(String personalNumber) {
        this.personalNumber = personalNumber;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
        }
    }

How should I complete my ModelLoginResponse POJO class for obtaining full server response???

like image 499
Choletski Avatar asked Nov 10 '22 10:11

Choletski


1 Answers

I know this is an old question and you probably already figured this out, but I will just post an answer here so that others might find it helpful.

For "lc" field, where the key value could be different for every response, you can use a Map data structure such as HashMap.

You can use the same Map structure for "stg" field, but if you know that the keys will be always the same, it's often better to create another POJO class for that item.

In short, your response will be something like:

@Parcel
public class ModelLoginResponse {
    @SerializedName("pn")
    private String personalNumber;

    @SerializedName("tk")
    private String token;

    @SerializedName("lc")
    private HashMap<String, String> lcMap;

    @SerializedName("stg")
    private StgResponse stgResponse;

    //add getters and setters if you need them.
}        

where StgResponse will be something like:

public class StgResponse {
    @SerializedName("rs")
    private Integer rs;

    @SerializedName("sml")
    private String sml;

    @SerializedName("ssl")
    private String ssl;

    //Getters and setters
}

Hope this helps.

like image 147
Byung Jun Kim Avatar answered Nov 14 '22 22:11

Byung Jun Kim