gpt4 book ai didi

php - Volley Json 请求不起作用 - 字符串无法转换为 JsonObject/JsonArray

转载 作者:行者123 更新时间:2023-11-30 00:38:50 25 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序并从服务器获取 JsonObject/JsonArray。手动将 String 转换为 Json 就可以了。
我最近切换到 Volley 来处理服务器请求,并想使用 JsonObjectRequest/JsonArrayRequest(而不是普通的 StringRequest)直接获取 json,而不必费心转换首先是字符串(这就是 Json 请求的目的,对吧?)。但是,代码总是在 onErrorResponse 中结束,并出现 ParseError 表示 String 无法转换为 JsonObject/JsonArray(即使语法看起来完全没问题)。我试图通过将服务器响应转换为 UTF8(如建议的 here )来消除潜在的“不可见”字符,但似乎也没有解决问题。此外,iOS 版本似乎没有任何相同响应的问题(我知道底层解析算法可能非常不同)。

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

最佳答案

好的,我找到了答案。 JsonObjectRequest/JsonArrayRequest 将额外的 JsonObject/JsonArray 对象作为参数。在大多数在线示例代码中,此参数设置为 null,我也这样做了,因为我不想发送 Json,只想接收。现在在 Volley Json 请求的幕后(非常不直观地)发生的事情是,如果此参数为空,则请求不是作为 POST 请求完成的,而是作为 GET 相反。这导致我的请求失败并且服务器返回错误代码而不是 json。这样的错误代码当然无法解析为json。我发现在 Volley 中默认实现的选择非常糟糕。

无论如何,解决方案就像引入一个 CustomJsonObjectRequest 一样简单,它与库中的实现非常相似,只是它坚持使用 POST 请求:

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

}

关于php - Volley Json 请求不起作用 - 字符串无法转换为 JsonObject/JsonArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com