How convert a String response to an iterable object

☆樱花仙子☆ 提交于 2020-12-21 02:04:47

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/65000363/how-convert-a-string-response-to-an-iterable-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!