Danish Danish - 8 days ago 6
Android Question

Android Retrofit reading a JSON object

I have a clean and simple question how to read this using Android Retrofit 2.0

{
"status": true,

"body": {

"expertises": {
"1": "Family Law",
"2": "Land and Asset",
"3": "Sexual Offense"
}
}
}


I want to read "expertises"

I have used model classes as follows:
Expertises:

public class Expertises {
@SerializedName("status")
private String status;
@SerializedName("expertises")
ExpertisesResponse expertisesResponse;

public ExpertisesResponse getExpertisesResponse() {
return expertisesResponse;
}

public void setExpertisesResponse(ExpertisesResponse expertisesResponse) {
this.expertisesResponse = expertisesResponse;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}
}


ExpertisesResponse:

public class ExpertisesResponse {

@SerializedName("1")
private String expertiseOne;
@SerializedName("2")
private String expertiseTwo;
@SerializedName("3")
private String expertiseThree;

public String getExpertiseOne() {
return expertiseOne;
}

public ExpertisesResponse(String expertiseOne, String expertiseTwo, String expertiseThree) {
this.expertiseOne = expertiseOne;
this.expertiseTwo = expertiseTwo;
this.expertiseThree = expertiseThree;
}



public String getExpertiseTwo() {
return expertiseTwo;
}

public String getExpertiseThree() {
return expertiseThree;
}

public void setExpertiseOne(String expertiseOne) {
this.expertiseOne = expertiseOne;
}

public void setExpertiseTwo(String expertiseTwo) {
this.expertiseTwo = expertiseTwo;
}

public void setExpertiseThree(String expertiseThree) {
this.expertiseThree = expertiseThree;
}
}


But I am getting Exception NullPointer for ExpertisesResposne. PLease I want some improvement or correction if anything is wrong.

This is how I called :

ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<Expertises> getExpertises = apiInterface.getExpertise();
getExpertises.enqueue(new Callback<Expertises>() {
@Override
public void onResponse(Call<Expertises> call, Response<Expertises> response) {

Toast.makeText(getApplicationContext(),response.body().getExpertisesResponse().getExpertiseOne(),Toast.LENGTH_SHORT).show();

}

@Override
public void onFailure(Call<Expertises> call, Throwable t) {

}
});
}

Answer

You missed class Body covering class ExpertisesResponse. Should be like:

class Body {

@SerializedName("expertises")
    ExpertisesResponse expertisesResponse;

}

And class Expertises

public class Expertises {
    @SerializedName("status")
    private String status;
    @SerializedName("body")
    Body body;
}