正如@Ridcully 所说,这是一个糟糕的 API 设计。由于您无法修改 API,解决方法是使用继承并将自定义 typeAdapter 添加到 Gson 实例。
请注意 SuccessResponse 和 FailureResponse "is-a" Response。当您对Response 类使用typeAdapter 时,自定义反序列化器将根据Response.meta.status 的值来确定该对象应该被反序列化为SuccessResponse 类还是FailureResponse 类。
响应父类
public class Response{
private Meta meta;
public Meta getMeta(){ return meta; }
public void setMeta(Meta meta){ this.meta = meta; }
}
成功响应子类
public class SuccessResponse extends Response{
private SuccessContent body;
public SuccessContent getSuccessContent() { return body; }
public void setSuccessContent(SuccessContent content) { this.body = content }
}
失败响应子类
public class FailureResponse extends Response{
private List<FailureContent> body;
public List<FailureContent> getBody() { return body; }
public void setObjList(List<FailureContent> content) { this.body= content; }
}
成功内容类
public class SucessContent{
//Model class of the success body
}
失败内容类
public class FailureContent{
private String errorCode;
private String errorMessage;
private String property;
private String args;
public String getErrorCode() { return errorCode; }
public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
public String getErrorMessage() { return errorMessage; }
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage;}
public String getProperty() { return property; }
public void setProperty(String property) { this.property = property; }
public String getArgs() { return args; }
public void setArgs(String args) { this.args = args; }
}
元类
public class Meta{
private String timestamp;
private String status;
public String getTimestamp() { return this.timestamp; }
public void setTimestamp(String timestamp) { this.timestamp = timestamp; }
public String getStatus() { return this.status; }
public void setStatus(String status) { this.status = status; }
}
用于反序列化响应类的 Gson 自定义类型适配器
public class ResponseBodyAdapter implements JsonDeserializer<Response> {
@Override
public Response deserialize (JsonElement json, Type typeOfT, JsonDerializationContext context) throws JsonParseException{
JsonObject obj = json.getAsJsonObject();
JsonObject metaObj = obj.getAsJsonObject("meta");
String status = metaObj.get("status").getAsString();
if(status.equals("OK")){
return context.deserialize(json, SuccessResponse.class);
}else if(status.equals("VALIDATION_ERROR")){
return context.deserialize(json, FailureResponse.class);
}
return null;
}
}
将类型适配器注册到 gson 并进行改造
Gson gson = new GsonBuilder()
.registerTypeAdapter(Response.class, new ResponseBodyAdapter ())
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();