Search code examples
androidretrofit

parse Json response in retrofit


The response of the call from WebService is as follows:

{
    "mobilenumber": "09999999999", 
    "service": "1" , 
    "id": "1"
}

How do I parse received Json into objects?

@Override
public void onResponse(Call<Login> call, Response<Login> response) {

    if (response.isSuccessful()) {

    } 
}

Solution

  • Assuming you have a LoginResult model like this:

    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
        
    public class LoginResult {
        
        @SerializedName("mobilenumber")
        @Expose
        private String mobilenumber;
        
        @SerializedName("service")
        @Expose
        private String service;
    
        @SerializedName("id")
        @Expose
        private String id;
        
        public String getMobilenumber() {
            return mobilenumber;
        }
        
        public void setMobilenumber(String mobilenumber) {
            this.mobilenumber = mobilenumber;
        }
        
        public String getService() {
            return service;
        }
        
        public void setService(String service) {
            this.service = service;
        }
        
        public String getId() {
            return id;
        }
        
        public void setId(String id) {
            this.id = id;
        }
        
    }
    

    Then, your Retrofit onResponse() method should be something like this:

    @Override
    public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
    
        if (response.isSuccessful()) {
            
            LoginResult result = response.body();
    
            String mobileNumber = result.getMobilenumber();
            String service = result.getService();
            String id = result.getId();
        } 
    }