简体   繁体   中英

Retrofit parse JSON response from API when model is in “data” object

How can I parse this response without having to create a separate response class for each entity.

{
  "data": {
    "id": 100,
    "first_name": "Michael",
    "last_name": "Blankenship"
  }
}

I would like to have a generic class that can reference the data object and then just specify what type of class that should be used to parse the response

Something like this:

@Get
Call<User> getUser();

@Get
Call<Status> getStatus();

Without having to have multiple response classes for each type

public class UserResponse {
    User data;
}

public class User {
    String first_name;
    String last_name;
}

public class StatusResponse {
    Status data;
}

Workaround for this would create a generic class something like this

public class BaseResponseWrapper <T> {

    @SerializedName("data")
    private T data;

    public BaseResponseWrapper(){
        super();
    }

    public T getData() {
        return data;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM