2017-07-07 35 views
0

我正在使用Android和DRF,現在進行翻新。如何使用Android版翻新工具獲取JSON對象

我想要使用Retrofit來獲取Django模型,它會返回JSON響應。

但在我的模型中,有多個JSON對象。

例如,

請求URL是[object1的URL]

響應= { Object2的:[Object2的網址], 一些其它數據(多個) }

如何使用Retrofit將object2更改爲json對象?


編輯

我解決了使用多的AsyncTask這個問題。 獲取Object1和object2的url,並在onPostExecute中創建一些新的AsyncTask,通過Retrofit獲取Object2,檢查Object2的url和Object2的列表參數'url'並進行匹配。 例如,

AsyncTask() { 
    doInBackground() { 
    get object1List 
    } 
    onPostExecute(object1List) { 
    AsyncTask2() { 
     doInBackground() { 
     get object2List 
     for (object1 : object1List) 
      object2ListItem & object1.url match 
     } 
     onPostExecute() { 
     something to do 
     } 
    } 
    } 
} 
+0

您可以從服務器原始答案中獲取並使用GSON庫進行解析 - https://github.com/google/gson。 –

回答

0

我建議你接收原始JSON,然後用GSON

private static Retrofit retrofit = null; 
private static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setLenient().create(); 

public static Retrofit getClient(String baseUrl) { 
     if (retrofit==null) { 
      retrofit = new Retrofit.Builder() 
        .baseUrl(baseUrl) 
        .addConverterFactory(GsonConverterFactory.create(gson)) 
        .client(httpClient.build()) 
        .build(); 
     } 
     return retrofit; 
    } 

解析和創建一個類,其中得到了預期的信息例如

public class People{ 
    @Expose 
    private String Name; 
    @Expose 
    private Int Age; 
    @Expose 
    private String Surname; 

// setters and getters... 

的API接口

public interface APIService { 
@POST("people.php") 
    Call<whatyoureceive> response(); 

} 

而且

private static final String BASE_URL = "YOUR URL"; 

public static APIService getAPIService() { 

    return RetrofitClient.getClient(BASE_URL).create(APIService.class); 
} 

在你的活動

private APIService mAPIService; 

mAPIService = ApiUtils.getAPIService(); 



public void sendRequest() { 
     mAPIService.responseo().enqueue(new Callback<PlanDetails>() { 
@Override 
      public void onResponse(......) { 
// what you want to do 
} 
@Override 
      public void onFailure(.....) { 
// what you want to do 
} 

更多信息https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

希望幫助!