简体   繁体   English

当模型位于“数据”对象中时,从API进行改造以解析JSON响应

[英]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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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