我正在学习如何在我的项目中实现 Json 并拥有以下 Json 文件:
{
"stations":[
{
"station":"no1",
"temperature":"xx",
"windchill":"yy"
},
{
"station":"no2",
"temperature":"xx",
"windchill":"yy"
},
{
"station":"no2",
"temperature":"xx",
"windchill":"yy"
}
]
}
我能够成功地在 TextView 中显示所有值,但我只对 1 号站感兴趣。如何在 textView 中仅传递来自 1 号站的值?
这是我的 Json 代码:
try {
JSONObject jsonObject = new JSONObject(contents);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject stations = jsonArray.getJSONObject(i);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
}
} catch (JSONException e) {
e.printStackTrace();
}
最佳答案
而不是使用
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject stations = jsonArray.getJSONObject(i);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
}
你可以做到
JSONObject stations = jsonArray.getJSONObject(0);
String station = stations.getString("station");
String temperature = stations.getString("temperature");
String temperature = stations.getString("windchill");
这样您将只能获取 JSON 中第一个元素的值。
关于java - 从 Json 文件调用单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55187680/