2015-08-24 36 views
0

所以,我認爲這是一個非常簡單的解決方案,我可能只是在想它。使用Retrofit從一個鍵提取不同的數據

我訪問的API,並出現以下JSON結構回:

{ 
    "request": 
    { 
    //request stuff 
    }, 
    "errors": 
    [ 
    //if there are any errors, it will show here 
    ], 
    "code": 200, 
    "response": 
    [ 
    //this can be an array or an object 
    ] 
} 

所以,如果我問一個用戶時,「反應」成爲一種含有一個鍵一個JSON對象「登錄」和我可以從中獲取用戶數據。但是,如果我要求一個圖片列表,「響應」是一個圖片對象的json數組。

你會如何建議我使用Retrofit/GSON創建POJO?

我想出的解決方案是創建一個包含請求,錯誤,代碼和響應的抽象ApiResponse類。響應將是其他類可以實現的接口。因此,例如與用戶:

public class UserApiResponse extends ApiResponse 

    private int code; 
    private List<String> errors; 
    private UserResponse response; 

而且UserReponse會是這樣的:

public class UserResponse extends Response 

    //has all user data 

將這項工作?或者有更好的方法去解決這個問題嗎?

回答

1

我認爲使用泛型的ApiResponse更好的方法。你ApiResponse可以像

public class ApiResponse<T extends Response> 
    private int code; 
    private List<String> errors; 
    private T response; 

改造調用會是這樣

@GET("/example/") ApiResponse<UserResponse> getUsers(); 
+0

我會嘗試一下,讓你知道。使用仿製藥改造POJO不會有困難嗎? – Sree

+1

@Sree我在我的項目中使用泛型與改造,沒有麻煩。 – fisher3421

相關問題