Json请求不起作用

Json请求不起作用

本文介绍了Volley Json请求不起作用-字符串无法转换为JsonObject/JsonArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序,并从服务器获取JsonObject/JsonArray.手动将String转换为Json可以.
我最近切换到Volley来处理服务器请求,并想使用JsonObjectRequest/JsonArrayRequest(而不只是普通的StringRequest)直接获取json,而不必费心先转换字符串(这就是Json Requests的意思)为,对吧?).但是,代码始终以onErrorResponse结尾,并带有一个ParseError表示String cannot be converted to a JsonObject / JsonArray(尽管语法似乎完全可以).我已尝试通过将服务器响应转换为UTF8来消除潜在的不可见"字符(如建议的此处),但似乎也无法解决问题.同样,iOS版本似乎在相同的响应上没有任何问题(我知道底层的解析算法可能有很大的不同).

I am working on an Android app and getting JsonObject/JsonArray from the server. Converting the String to Json manually works ok.
I recently switched to Volley for server requests, and want to use JsonObjectRequest / JsonArrayRequest (rather than just plain StringRequest) to get the json directly and not have to bother about converting the string first (that's what the Json Requests were made for, right?).However, the code always ends up in onErrorResponse with a ParseError saying that the String cannot be converted to a JsonObject / JsonArray (even though syntax seems totally ok).I have tried to eliminate potential "invisible" characters by converting the server response to UTF8 (as suggested here ) but doesn't appear to solve the problem either. Also, the iOS version does not seem to have any issues with the same responses (I know that the underlying parsing algorithm may be very different).

当然,使用StringRequests或发出自定义请求就可以完成这项工作(正如其他一些stackoverflow讨论中所建议的那样),但这使我很烦恼,无法使Json Requests正常工作.有人也有这个问题吗?得知潜在的原因和解决方案将非常高兴!

Of course, working with StringRequests or making custom requests would do the job (as suggested in a few other stackoverflow discussions), but it just bugs me a lot that I cannot get Json Requests to work. Anyone had this problem as well? Would be great to hear about potential causes and solutions!

推荐答案

好,我找到了答案. JsonObjectRequest/JsonArrayRequest接受另一个JsonObject/JsonArray对象作为参数.在大多数在线示例代码中,此参数都设置为null,我也这样做了,因为我不想发送Json,而只是希望接收.现在,在Volley Json请求的幕后发生的事情(直觉上是相当多的)是,如果此参数为null,则该请求不会作为POST请求执行,而是作为GET请求执行.这导致我的请求失败,服务器返回错误代码而不是json.反过来,此类错误代码也无法解析为json.我发现Volley的默认实现是非常糟糕的选择.

Ok, I found the answer. The JsonObjectRequest / JsonArrayRequest take an additional JsonObject / JsonArray object as an argument. In most sample codes online, this argument is set to null and I did the same because I did not want to send a Json, only to receive.Now what happens (quite unintuitively) behind the scenes of the Volley Json requests, is that if this argument is null the request is not done as a POST request, but as a GET instead. This caused my request to fail and the server to return an error code rather than a json. Such an error code in turn could not be parsed to a json of course.Very bad choice for a default implementation in Volley I find.

无论如何,该解决方案就像引入CustomJsonObjectRequest一样容易,它与库中的实现非常相似,不同之处在于它坚持使用POST请求:

In any case, the solution was as easy as introducing a CustomJsonObjectRequest which is very similar to the implementation from the library, except that it sticks with the POST request:

public class CustomJsonObjectRequest extends Request<JSONObject> {

protected static final String PROTOCOL_CHARSET = "utf-8";

private final Response.Listener<JSONObject> mListener;

public CustomJsonObjectRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
    super(Method.POST, url, errorListener);
    mListener = listener;
}

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

  @Override
  protected void deliverResponse(JSONObject response) {
    mListener.onResponse(response);
  }

}

这篇关于Volley Json请求不起作用-字符串无法转换为JsonObject/JsonArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:38