在android中发布Json对象数据以获得Json数组响应

时间:2022-10-22 19:50:50

I need to post JSONObject (using Volley) to a web-service which is returning the response in JSONArray format.

我需要将JSONObject(使用截击)发布到一个web服务,该服务以JSONArray格式返回响应。

Here is what I have tried so far.

这是我到目前为止所尝试的。

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
    }
};

But I'm getting JSONException saying that JSONArray cannot be converted to JSONObject. Is there a way to get the response in JSONArray format? What is the best possible solution for my problem? How can I send JSONObject if I use StringRequest instead of JsonObjectRequest? Please guide me

但是我得到了JSONException声明JSONArray不能被转换为JSONObject。是否有方法以JSONArray格式获取响应?对于我的问题,最好的解决方案是什么?如果我使用StringRequest而不是JsonObjectRequest,如何发送JSONObject ?请指导我

3 个解决方案

#1


11  

Below helper class has fixed my problem

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

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));
    }
}

 }

How to use this?

如何使用呢?

    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);

#2


0  

Looks like you are getting the json array response.

看起来你得到了json数组响应。

Can you change your code like this.

你能改变你的代码吗?

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

#3


-1  

try this one

试试这个

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);

#1


11  

Below helper class has fixed my problem

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

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));
    }
}

 }

How to use this?

如何使用呢?

    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);

#2


0  

Looks like you are getting the json array response.

看起来你得到了json数组响应。

Can you change your code like this.

你能改变你的代码吗?

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

#3


-1  

try this one

试试这个

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);