我遇到了语法问题,但我无法弄清楚出了什么问题。看起来这个帖子有答案,但它对我有用。
JSONException: Value of type java.lang.String cannot be converted to JSONObject
我正在使用Volley我需要扩展JsonObjectRequest,以便我可以访问响应中的http标头。这是我的“CustomRequest”
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));
如果有人能发现这个问题,我非常感谢。
THX!
答案 0 :(得分:0)
thx boukharist,
上面的url没有提供有效的json文件。我改为:
String url =“http://httpbin.org/get?site=code&network=tutsplus”;
它有效!