Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between JSONRequest and StringRequest in volley

I have always read that data comes from server in json format also when we want to send some data we send to the server in json format so data travels in json format then where string request comes from? I dont know if we can post and get data in string format also, and what is the difference and use cases for using string and json requests?

Thanks!

like image 909
blackHawk Avatar asked Aug 07 '17 09:08

blackHawk


People also ask

What is Stringrequest?

A canned request for retrieving the response body at a given URL as a String.

What is JsonObjectRequest?

JsonArrayRequest : A request for retrieving a JSONArray response body at a given URL. JsonObjectRequest : A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.


2 Answers

StringRequest class will be used to fetch any kind of string data. The response can be json, xml, html,text.

 // Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
});

If you are expecting json object in the response, you should use JsonObjectRequest .

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
            URL, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
like image 62
IntelliJ Amiya Avatar answered Oct 19 '22 20:10

IntelliJ Amiya


It's about the return type from the request, StringRequest handles a String as response like error = false and JSONObjectRequest handles a JSONObject response like {"error" : false}, how to know it's JSONObject ? with the usage of brackets ({).

like image 28
Oussema Aroua Avatar answered Oct 19 '22 19:10

Oussema Aroua