我想在android studio中使用Asynctask帮助在其中发布嵌套对象的JSON数据,但我不熟悉android studio中的API实现。我是android studio的新手。我已经成功地从POSTMAN发布了这些数据,但是我无法为它实现代码,我也没有任何Asynctask的教程。请帮我实现此代码。
这是我的Json数据,其中包含嵌套对象:
答案 0 :(得分:0)
现在更好/更简单的方法是使用像Retrofit这样的图书馆来为你做所有的魔术。
您只需将Java实例模型发送到API端点即可。在使用GsonConverterFactory类时,Retrofit负责将其转换为json,并将json发送到您使用给定HTTP方法提供的端点。
答案 1 :(得分:0)
您不需要异步,Volley会在后台为您执行此操作。将JSONObject放在方法中而不是新的JSONObject'中。和YourURL - 即' / api / route /'。
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request_json = new JsonObjectRequest(YourURL, new JSONObject(params)),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
//Do what you want on response
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If there's an error...
}
});
//Add process to queue to get JSON in background thread
queue.add(request_json);
答案 2 :(得分:0)
由Square制作的第三方库实施API服务的最佳和简单库,改造Easy HTTP客户端。
为什么要改造?因为,Retrofit自动创建后台线程,使用GSON转换器解析Json并直接在主线程上调用成功和失败。没有编写太多的AsyncTask和Parsing JSON的样板代码并在主线程上获得结果。
改造客户。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
RetrofitInterface service = retrofit.create(RetrofitInterface.class);
在RetrofitInterface中创建方法。
@POST("users/new")
Call<User> yourMethod(@Body UserType user);
现在调用您的方法,它将使您的成功和失败回调方法
Call<List<Repo>> repos = service.yourMethod("octocat");
然后调用enque方法自动创建后台线程。
repos.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
}
@Override
public void onFailure(Call<MainResponse> call, Throwable t) {
}
});