【问题标题】:Post Json object data to get Json array response using volley in android在 android 中使用 volley 发布 Json 对象数据以获取 Json 数组响应
【发布时间】:2015-06-16 04:50:46
【问题描述】:

我需要将JSONObject(使用Volley)发布到以JSONArray 格式返回响应的网络服务。

这是我迄今为止尝试过的。

final JSONObject requestJsonObject = new JSONObject();
requestJsonObject.put("username", userName);
requestJsonObject.put("password", password);

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, ServiceUrls.LOGIN_URL, requestJsonObject, loginResponseListener, loginErrorListener);


private Listener<JSONObject> loginResponseListener = new Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject resposne) {
         //other stuff goes here
    }
};

但我收到JSONExceptionJSONArray 无法转换为JSONObject。有没有办法以JSONArray 格式获得响应?我的问题的最佳解决方案是什么?如果我使用StringRequest 而不是JsonObjectRequest,如何发送JSONObject?请指导我

【问题讨论】:

  • 你可以使用JsonArrayRequest
  • JsonArrayRequest 需要输入参数为 JSONArray,不适合这种情况

标签: android json http-post android-volley jsonobject


【解决方案1】:

下面的帮助类解决了我的问题

public class CustomRequest extends JsonRequest<JSONArray> {

protected static final String PROTOCOL_CHARSET = "utf-8";
/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param requestBody A {@link String} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public CustomRequest(int method, String url, String requestBody, Listener<JSONArray> listener, ErrorListener errorListener) {
    super(method, url, requestBody, listener, errorListener);
}

/**
 * Creates a new request.
 * @param url URL to fetch the JSON from
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public CustomRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
    super(Method.GET, url, null, listener, errorListener);
}

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public CustomRequest(int method, String url, Listener<JSONArray> listener, ErrorListener errorListener) {
    super(method, url, null, listener, errorListener);
}

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public CustomRequest(int method, String url, JSONArray jsonRequest, Listener<JSONArray> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public CustomRequest(int method, String url, JSONObject jsonRequest, Listener<JSONArray> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}

/**
 * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
 * <code>null</code>, <code>POST</code> otherwise.
 *
 * @see #MyjsonPostRequest(int, String, JSONArray, Listener, ErrorListener)
 */
public CustomRequest(String url, JSONArray jsonRequest, Listener<JSONArray> listener, ErrorListener errorListener) {
    this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, listener, errorListener);
}

/**
 * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
 * <code>null</code>, <code>POST</code> otherwise.
 *
 * @see #MyjsonPostRequest(int, String, JSONObject, Listener, ErrorListener)
 */
public CustomRequest(String url, JSONObject jsonRequest, Listener<JSONArray> listener, ErrorListener errorListener) {
    this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, listener, errorListener);
}

@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

 }

这个怎么用?

    JSONObject requestJsonObject = new JSONObject();
    requestJsonObject.put("first_name", firstName);
    requestJsonObject.put("last_name", lastName);
    requestJsonObject.put("email_address", emailId);
    requestJsonObject.put("password", password);

    CustomRequest jsonObjReq = new CustomRequest(Method.POST, YOUR_URL, requestJsonObject, responseListener, errorListener);

【讨论】:

  • @mahdipishguy:更新了我的回答
  • 我使用了你的代码并在添加到 requestQueue jsonObjReq 显示 null 但 requestjsonObject 包含这种类型的值 "{"id":"1"}" 所以是 Key价值对??如果它是一个 keyValue 对而不是在服务器端,我该如何检索它
  • Get 调用是如何工作的,我想得到 List 类型的响应
【解决方案2】:

看起来您正在收到 json 数组响应。

你能像这样改变你的代码吗?

  private Listener<JsonArray> loginResponseListener = new Listener<JsonArray>() {
         @Override
        public void onResponse(JsonArray resposne) {
         //other stuff goes here
        }
  };

【讨论】:

    【解决方案3】:

    试试这个

    RequestQueue request = Volley.newRequestQueue(this);
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,new Response.Listener<JSONArray>() 
            {
    
                @Override
                public void onResponse(JSONArray response) 
                {
                    List<Contact> result = new ArrayList<Contact>();
                    for (int i = 0; i < response.length(); i++) 
                    {
                        try
                        {
                            result.add(convertContact(response
                                    .getJSONObject(i)));
                        } 
                        catch (JSONException e)
                        {
    
                        }
                    }
                    adpt.setItemList(result);
                    adpt.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() 
            {
    
                @Override
                public void onErrorResponse(VolleyError error)
                {
                    // Handle error
                }
            });
    
    request.add(jsonArrayRequest);
    

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多