1

I am running into a syntax problem but I can't figure out what is wrong. It seems like this thread has the answer but it does work for me.

JSONException: Value of type java.lang.String cannot be converted to JSONObject

I am using Volley I need to extend the JsonObjectRequest so that I can access the http headers in the response. Here is my "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;
    }
}

and here my test class:

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

If I try the sample above I keep getting:

com.android.volley.ParseError: org.json.JSONException: Value <html><head><meta of type java.lang.String cannot be converted to JSONObject

but I am returning a JSONObject:

        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));

if anyone can spot the issue I greatly appreciate.

thx!

Community
  • 1
  • 1
gmmo
  • 2,577
  • 3
  • 30
  • 56

1 Answers1

0

thx boukharist,

the url above was not providing a valid json file. I changed to:

String url = "http://httpbin.org/get?site=code&network=tutsplus";

and it works!

gmmo
  • 2,577
  • 3
  • 30
  • 56