所以我使用aJsonObjectRequest向rest调用发送aJsonObject,但它返回aJsonArray而不是aJsonObject。它给了我一个错误,说它不能解析JsonObjectRequest的结果,但是如果我使用JsonArrayRequest我就不能在正文中发送JsonObject。如何发送aJsonObject但得到aJsonArray作为响应?

        RequestQueue queue = Volley.newRequestQueue(this);
    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,jsonBody,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    String test = "";
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

最佳答案

我最近面对这种情况,意识到截击并不能提供任何现成的解决方案。您已经创建了一个接受json对象请求并返回数组的自定义响应。一旦你创建了自己的类,你就可以做这样的事情。

 CustomJsonRequest jsonObjectRequest = new CustomJsonRequest(Request.Method.POST, url, credentials, new Response.Listener<JSONArray>(){...}



package com.example.macintosh.klickcard.Helpers.Network;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Created by yasinyaqoobi on 10/6/16.
 */

public class CustomJsonRequest<T> extends JsonRequest<JSONArray> {

    private JSONObject mRequestObject;
    private Response.Listener<JSONArray> mResponseListener;

    public CustomJsonRequest(int method, String url, JSONObject requestObject, Response.Listener<JSONArray> responseListener,  Response.ErrorListener errorListener) {
        super(method, url, (requestObject == null) ? null : requestObject.toString(), responseListener, errorListener);
        mRequestObject = requestObject;
        mResponseListener = responseListener;
    }

    @Override
    protected void deliverResponse(JSONArray response) {
        mResponseListener.onResponse(response);
    }

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

关于android - Android Volley,JsonObjectRequest但接收JsonArray,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35146570/

10-09 20:25