2017-02-03 78 views
0

比方说,我有一个REST API,可以通过调用以下改进2请求来获取书籍列表。通过改进处理动态响应的正确方法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; 
} 

我使用一个身份验证令牌给自己授权给API,因为它可以在我的要求可以看出。由于标记过期或其他原因,有时候会收到其他响应而不是上面的响应。例如:

{ 
    "status": "error", 
    "message": "Expired token" 
} 

在改造2中处理动态响应(具有已知结构)的正确方法是什么?

+1

如果您的令牌已过期,那么api应该返回一个错误代码401.并且您可以从那里继续。如果它返回200和一些错误有效负载,那么它是不正确的设计api。 –

回答

2

你有多种选择:

1 - 改变你的API:(这个人是标准)

改变它像这样每一个反应,如果用户认证失败离开的结果无效,或者认证成功地将结果列入清单。

{ 
"status" : "error/success" 
"message" : ... 
"result" : .... 
} 

2 - 你可以给Object类型改造,响应成功后,您可以使用语法“的实例”它投射到您的车型之一。

public interface AllRecordsFromRequestInterface { 
@GET("books/all") 
Call<Object> operation(@Header("Authorization") String authentication_token); 
}