android - 不显示带有响应的传入数据
问题描述
我正在为 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"}}
解决方案
使用这段代码。
@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();
}
}
推荐阅读
- json - 循环API直到满足条件
- excel - 更改代码以使用选择来填充数组
- bash - 从 bash 程序在后台执行静默 sqlplus
- javascript - 我通过 id 获取元素的 javascript 在一行上工作,但在另一行上却不行
- python - 如何循环和保存每次迭代的数据
- r - 计算每个类别的天数总和
- sql-server - 如何在我的过程中使用 where 语句并在 select 语句中使用开引号?
- reactjs - URL 中的多个参数
- r - 使用 case_when 长格式数据集 dplyr 进行变异
- java - 为什么我的基于 SOAP 的项目可以在不包含 Apache CXF 依赖项的情况下工作?