【问题标题】:How convert a String response to an iterable object如何将字符串响应转换为可迭代对象
【发布时间】:2021-03-08 01:17:39
【问题描述】:

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

 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 转换为可迭代对象?

【问题讨论】:

  • 你想要一个列表、字典还是什么?
  • 嗯,那是 JSON - 所以我会使用 JSON 库来解析它。
  • 任何可以迭代的都可以。
  • 我用过 Gson 。但这对我不起作用。

标签: java android json rest android-volley


【解决方案1】:

除了 Volley 之外,不需要任何其他库。

使用 Volleys 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);

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 2017-01-17
    • 2011-10-03
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2018-07-19
    相关资源
    最近更新 更多