I'm using Android and DRF, Retrofit now.
I'm trying to get Django models using Retrofit, It returns JSON Response.
But in my model, there is multiple JSON Objects.
For example,
request url is [object1's url]
and
response = { object2:[object2's url], some other data(s) }
How can I change object2 to json object using Retrofit?
Edit
I solved this issue using multiple AsyncTask. get Object1 and object2's url, and in onPostExecute, make some new AsyncTask, get Object2 by Retrofit, check Object2's url and Object2's list parameter 'url' and match. for example,
AsyncTask() {
doInBackground() {
get object1List
}
onPostExecute(object1List) {
AsyncTask2() {
doInBackground() {
get object2List
for (object1 : object1List)
object2ListItem & object1.url match
}
onPostExecute() {
something to do
}
}
}
}
i recommend you to receive the raw JSON and then parsing with 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;
}
and create a class where got the expected information example
public class People{
@Expose
private String Name;
@Expose
private Int Age;
@Expose
private String Surname;
// setters and getters...
the api interface
public interface APIService {
@POST("people.php")
Call<whatyoureceive> response();
}
Also
private static final String BASE_URL = "YOUR URL";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
In your activity
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
}
More information https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
Hope help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.