Java 使用Volley为JSON请求定制对象绑定
我正在研究凌空库,尤其是处理Java 使用Volley为JSON请求定制对象绑定,java,android,json,android-volley,Java,Android,Json,Android Volley,我正在研究凌空库,尤其是处理JSONObject请求。在一些教程中,我可以找到如下示例: JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) {
JSONObject
请求。在一些教程中,我可以找到如下示例:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// ...
}
}
, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// ...
}
});
JsonObjectRequest JSONObjectReq=新的JsonObjectRequest(Method.GET,
url,空,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
// ...
}
}
,new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
// ...
}
});
但现在我想知道是否有办法将自定义类绑定到请求对象或结果对象
我的意思是:我想将键值结果映射到我的应用程序域中的某个强类型自定义对象。这是可能的还是我应该自己实现这个功能?我想这会对您有所帮助
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Method.POST,url,your_json_object,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// On Success
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// On Failure
}
});
MyApplication.getInstance().addToRequestQueue(jsObjRequest, tag);
JsonObjectRequest jsObjRequest=新的JsonObjectRequest(Method.POST、url、您的_json_对象、,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
//论成功
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
//论失败
}
});
MyApplication.getInstance().addToRequestQueue(jsObjRequest,标记);
传递你的你的\u json\u对象
而不是我的对象
完成您可以像这样使用Gson库:
假设您的目标是获得一个名称对象,其中名称定义为
public class Name{
private String firstName;
private String middleName;
private String lastName;
//constructor, getter, setter
}
然后可以使用Gson将JSONObject转换为Name
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Gson gson = new Gson();
Name name = gson.fromJson(response.toString(),Name.class);
//use Name.
}
}
, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// ...
}
});
JsonObjectRequest JSONObjectReq=新的JsonObjectRequest(Method.GET,
url,空,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
Gson Gson=新的Gson();
Name Name=gson.fromJson(response.toString(),Name.class);
//使用名称。
}
}
,new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
// ...
}
});
@Lissf的答案是避免陈词滥调的好方法
但是,我建议您检查一下,它可以将问题简化为一行:
@GET ("/name")
getName(Callback<Name> nameCallback);
@GET(“/name”)
getName(callbacknamecallback);
你也可以去看看 您可以使用
Gson
将JSONObject
解组到自定义对象中。但是出于好奇,为什么不进行改造?@W.K.S我对安卓系统是新手,我正在评估一些库。我不知道改造lib。谢谢你的建议!哦,如果你对安卓系统还不熟悉,那就改头换面,永远不要回头。它确实节省了时间和代码+与Volley不同,它有更好的文档。