服务器返回以下JSON -
[ { " user_id":1, " first_name":" alex", " last_name":" goft", "密码":" doom00", "电子邮件":" alex@mail.com", "用户名":" alexgoft" } ]
我正在尝试使用以下函数使用volley来检索它 -
public void makeRequest() {
final String HOST = "http://10.0.2.2:3000/";
final String url = HOST + "get_data?type=user&username=alexgoft";
RequestQueue queue = Volley.newRequestQueue(context);
Toast.makeText(context, url, Toast.LENGTH_LONG).show();
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Toast.makeText(context, "In succ", Toast.LENGTH_LONG).show();
try {
returned_json = response.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "In error", Toast.LENGTH_LONG).show();
Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
error.getStackTrace();
Log.d("error", error.toString());
}
});
queue.add(getRequest);
}
问题是我收到以下错误 -
Error:(46, 40) error: no suitable constructor found for JsonObjectRequest(int,String,<anonymous Listener<JSONArray>>,<anonymous ErrorListener>)
constructor JsonObjectRequest.JsonObjectRequest(int,String,Listener<JSONObject>,ErrorListener) is not applicable
(argument mismatch; <anonymous Listener<JSONArray>> cannot be converted to Listener<JSONObject>)
constructor JsonObjectRequest.JsonObjectRequest(String,JSONObject,Listener<JSONObject>,ErrorListener) is not applicable
(argument mismatch; int cannot be converted to String)
我需要做什么才能使returned_json
包含来自主机的返回json?
这就是它在ide中的样子 -
答案 0 :(得分:1)
如果您没有任何数据可以传递请求,则需要传递null
注意:由于您的回复是JSONArray
,因此您需要实施JsonArrayRequest
而不是JsonObjectRequest
@Krupa Kakkad
new JsonObjectRequest(Request.Method.GET, url, null,
// ^^^^
new Response.Listener<JSONArray>() {
@param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
构造函数签名
public JsonObjectRequest(int method,String url,JSONObject jsonRequest, 侦听器侦听器,ErrorListener errorListener){
或
public JsonObjectRequest(String url,JSONObject jsonRequest, 听众听众, ErrorListener errorListener){
答案 1 :(得分:0)
您必须致电JsonArrayRequest
而不是JsonObjectRequest
。
供参考:https://www.androidhive.info/2014/09/android-json-parsing-using-volley/