首页 > 解决方案 > 不显示带有响应的传入数据

问题描述

我正在为 android 编写应用程序并使用 volley 库。我需要将接收到的数据写入TextResult. 怎么做?

private void jsonParse() {
        String url = "https://api.apixu.com/v1/current.json?key=...&q=Paris";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("location");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject location = jsonArray.getJSONObject(i);
                                String name = location.getString("name");
                                String region = location.getString("region");
                                String country = location.getString("country");
                                TextResult.append(name + ", " + region + ", " + country + "\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
    }

Json 响应示例

{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}

标签: androidandroid-volley

解决方案


使用这段代码。

@Override
    public void onResponse(JSONObject response) {
        try {
            JSONObject jsonObject = response.getJSONObject("location");

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONArray location = jsonObject.getJSONArray(i);
                String name = location.getString("name");
                String region = location.getString("region");
                String country = location.getString("country");
                TextResult.append(name + ", " + region + ", " + country + "\n\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

推荐阅读