如何将字符串响应转换为可迭代对象

3

我正在尝试在Android/Java应用程序中使用Volley(HTTP库)调用REST端点。这是我的代码:

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

但是它给我返回了一个像这样的字符串响应:

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

我怎样将这个 String 转换为可迭代对象?


1
你想要一个列表、字典还是其他什么? - topsoftwarepro
2
那就是JSON - 所以我会使用一个JSON库来解析它。 - Jon Skeet
任何可迭代的东西都可以。 - Shihara Dilshan
我使用了Gson。但是它对我不起作用。 - Shihara Dilshan
1个回答

4

除了Volley库之外,无需使用其他库。

使用Volley的JsonArrayRequest来检索JSONArray响应。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接