Search code examples
javajsonclassgsonpojo

Gson parse to subclass that overrides variable


I want to make some response POJO classes which I will receive from my webserver.

My webserver will always return a json in this structure:

{
    'data':Object or array or null,
    'status':Integer,
    'message':String or null
}

This is the BaseResponse:

public class BaseResponse {
    private Object data;
    private int status;
    private String message;

    public Object getData() { return this.data; }
    public int getStatus() { return this.status; }
    public String getMessage() { return this.message; }
}

Then I have one 'real' response class:

public class LoginResponse extends BaseResponse {
    private UserData data;

    @Override
    public UserData getData() { return data; }
}

UserData is another class that looks exactly like these but with different variable names (id and name).

I try to parse the response like this:

try {
    LoginResponse json = gson.fromJson(jsonString, LoginResponse.class);
    Log.i(PF.TAG, "ID: " + json.getData().getName());
}

But it throws an exception on fromJson() saying:

LoginResponse declares multiple JSON fields named data

How can I fix this and still have the data variable in BaseResponse?


Solution

  • You can use generic types.

    public class BaseResponse<T> {
    
        private T data;
        private int status;
        private String message;
    
        public T getData(){
            return this.data;
        }
    
        public int getStatus(){
            return this.status;
        }
    
        public String getMessage(){
            return this.message;
        }
    }
    

    An example response type:

    public class LoginResponse extends BaseResponse<UserData>{
    
    }
    

    then you can use:

    LoginResponse json = gson.fromJson(jsonString, LoginResponse.class);
    Log.i(PF.TAG, "ID: " + json.getData().getName());
    

    With this method T can be any object you wish.