假设我有一个 REST API,我可以通过调用以下改造 2 请求来获取图书列表。
public interface AllRecordsFromRequestInterface {
@GET("books/all")
Call<List<TrackInfo>> operation(@Header("Authorization") String authentication_token);
}
和 API 响应:
[
{
"id": "1",
"title": "The Catcher in the Rye",
"author":"J. D. Salinger"
},
{
"id": "2",
"title": "The Great Gatsby",
"author":"F. Scott Fitzgerald"
}
]
我使用GsonConverterFactory
将json转换为模型。这是我的模型类
public class Book{
private int id;
private String title;
private String author;
}
我正在使用身份验证 token 向自己授权 API,正如我的请求中所见。有时,由于 token 过期或其他原因,会收到其他响应而不是上述响应。例如:
{
"status": "error",
"message": "Expired token"
}
改造 2 中处理动态响应(具有已知结构)的正确方法是什么?
最佳答案
您有多种选择:
1-更改您的 API:(这是标准的)
对每个响应进行这样的更改,如果用户身份验证失败,则将结果保留为空,或者如果身份验证成功,则将列表放入结果中。
{
"status" : "error/success"
"message" : ...
"result" : ....
}
2-您可以提供要改造的对象类型,响应成功后,您可以使用“实例”语法将其转换为您的模型之一。
public interface AllRecordsFromRequestInterface {
@GET("books/all")
Call<Object> operation(@Header("Authorization") String authentication_token);
}
关于java - 通过改造 2 处理动态响应的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42030665/