我遇到了语法问题,但我不知道出了什么问题。似乎这个线程有答案,但它确实对我有用。
JSONException:java.lang.String 类型的值无法转换为 JSONObject
我正在使用 Volley 我需要扩展 JsonObjectRequest 以便我可以访问响应中的 http 标头。这是我的“自定义请求”
public class CustomRequest extends JsonObjectRequest {
public CustomRequest(int method, String url, String jsonRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
// Save http headers
mHeaders = response.headers;
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));
}
}
private Map<String, String> mHeaders = new HashMap<>();
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return mHeaders;
}
}
这里是我的测试课:
private void testVolleyRequest() {
String url = "http://my-json-feed";
CustomRequest jsonRequest = new CustomRequest
(Request.Method.GET, url, (String)null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("[TEST]", "Response: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("[TEST]", "error = "+error.toString());
}
});
Volley.newRequestQueue(this).add(jsonRequest);
}
如果我尝试上面的示例,我会不断得到:
com.android.volley.ParseError: org.json.JSONException: Value <html><head><meta of type java.lang.String cannot be converted to JSONObject
但我返回一个 JSONObject:
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
如果有人能发现这个问题,我将不胜感激。
谢谢!