Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert a String response to an iterable object

I am trying to call a rest end point using Volley (HTTP library) in Android/Java app. Here is my code,

 RequestQueue queue = Volley.newRequestQueue(this);
        String url ="https://covid19datasl.herokuapp.com/countries";


        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println(response);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println("Error");
            }
        });

But it gives me an String a response like this,

[{"country":"USA","countryCode":"US"},{"country":"India","countryCode":"IN"},{"country":"Brazil","countryCode":"BR"}]

How do I convert this String to an itaratable object?

like image 280
Shihara Dilshan Avatar asked Dec 19 '25 11:12

Shihara Dilshan


1 Answers

No need for any other libraries beside Volley.

Use Volleys JsonArrayRequest for retrieving JSONArray responses.

RequestQueue queue = Volley.newRequestQueue(this);

String url = "http://my-json-feed";

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {
        // do something with the response
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO: Handle error
    }
});

// Add request to queue 
queue.add(jsonArrayRequest);
like image 51
David Kroukamp Avatar answered Dec 22 '25 06:12

David Kroukamp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!