7

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!

blackHawk
  • 6,047
  • 13
  • 57
  • 100
  • 2
    https://stackoverflow.com/questions/32420158/jsonrequest-vs-stringrequest-in-android-volley – IntelliJ Amiya Aug 07 '17 at 09:26
  • unfortunately It didn't help – blackHawk Aug 07 '17 at 09:27
  • JSONRequest returns the result as a JSONObject. The StringRequest returns the result as a String(the json structure on a string) – Stamatis Stiliats Aug 07 '17 at 09:30
  • so whole json response is returned in string format? – blackHawk Aug 07 '17 at 09:32
  • If you expect the response to be a JSON object or a JSON Array, save time from implementing serialization and you don't want to explicitly set the content type then `JsonObjectRequest` and `JsonArrayRequest` is the right tool you need. However if it is a different format or you just wanted to use some other serialization/deserialization tool like GSON then the `StringRequest` is the general tool for that. Well so far Volley is lacking of `ByteRequest`. – Enzokie Aug 07 '17 at 10:02

2 Answers2

8

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) {

                }
            });
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

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 ({).

Oussema Aroua
  • 5,225
  • 1
  • 24
  • 44