Search code examples
javaandroidgsonretrofit2pojo

POJO class from JSON for Retrofit2 Callback


{
   "success":true,
   "userobject":{
       "username":"user",
       "email":"user@gmail.com",
       "password":"user123"
    }
}

This is my JSON. I want to create POJO class from this. Now i have something like this:

public class LoginResponse
{
    @SerializedName("success")
    @Expose
    private Boolean success;

    @SerializedName("username")
    @Expose
    private String username;

    @SerializedName("email")
    @Expose
    private String email;

    @SerializedName("password")
    @Expose
    private String password;

    public Boolean getSuccess() {
        return success;
    }

    public String getUsername() {
        return username;
    }

    public String getEmail() {
        return email;
    }

    public String getPassword() {
        return password;
    }
}

I want access to fields like "username", "email", "password" in Retrofit Callback:

 final LoginRequest loginRequest = new LoginRequest(email, password);
        Call<LoginResponse> call = service.login(loginRequest);

        call.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response)
            {
                if(response.isSuccessful()) {
                    background.setImageResource(R.drawable.bg_login_screen);
                    progressBar.setVisibility(View.GONE);

                    Toast.makeText(LoginActivity.this, response.body().getEmail(), Toast.LENGTH_SHORT).show();
                }

And it doesn't work. I can access to "success" field of course only. How it POJO class should look like?


Solution

  • userObject is a new object, you should create a new class to access it:

    public class LoginResponse {
        @SerializedName("success")
        @Expose
        private Boolean success;
    
        private UserObject userobject;
    
    
        public Boolean getSuccess() {
            return success;
        }
    
        public UserObject getUserObject() {
           return userobject;
        }
    }
    

    And

    public class UserObject {
        @SerializedName("username")
        @Expose
        private String username;
    
        @SerializedName("email")
        @Expose
        private String email;
    
        @SerializedName("password")
        @Expose
        private String password;
    
        public String getUsername() {
            return username;
        }
    
        public String getEmail() {
            return email;
        }
    
        public String getPassword() {
            return password;
        }
    }