spurthi
spurthi

Reputation: 173

Using Android Volley for Json request and response as String

I have a situation where am using the Android-volley to POST my json object , I could able to successfully post all contents and my data is visible in server but server responds as String not as json , this is the reason am getting error.

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

So is possible in volley to parse strings when we pass json objects ?? My working code is below,

            HashMap<String, String> params = new HashMap<String, String>();
    params.put("email", "[email protected]");
    params.put("password", "qweffrty");
    params.put("name", "Dudeb");
    params.put("place", "Bangalore");
    params.put("phone", "991000000000");

    JsonObjectRequest request = new JsonObjectRequest(
            Request.Method.POST,
            Constants.BASE_URL+"register",
            new JSONObject(params),
            createSuccessListener(),
            createErrorListener());


         private static Response.Listener<JSONObject> createSuccessListener() {
    return new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            // TODO parse response

            String test;
            test = "yyy";
        }
    };
}

private static Response.ErrorListener createErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          //  Log.d(TAG, "Error Response code: " + error.getMessage());
            String test;
            test = "yyy";
        }
    };
}

Upvotes: 4

Views: 4026

Answers (1)

mmlooloo
mmlooloo

Reputation: 18977

No because look at these lines in implementation, in JsonRequest we have:

public abstract class JsonRequest<T> extends Request<T>
...
abstract protected Response<T> parseNetworkResponse(NetworkResponse response);

and in JsonObjectRequest we have:

public class JsonObjectRequest extends JsonRequest<JSONObject>

and look at the response defination in JsonObjectRequest:

protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)

so if you want to use JsonObjectRequest of volley library you send json and deliver json. you can use StringRequest instead.

Upvotes: 1

Related Questions