从Json文件调用单个对象

时间:2019-03-15 17:13:56

标签: java json

我正在学习如何在项目中实现Json并拥有以下Json文件:

{
   "stations":[
      {
         "station":"no1",
         "temperature":"xx",
         "windchill":"yy"
      },
      {
         "station":"no2",
         "temperature":"xx",
         "windchill":"yy"
      },
      {
         "station":"no2",
         "temperature":"xx",
         "windchill":"yy"
      }
   ]
}

我能够在TextView中成功显示所有值,但是我只对站号no1感兴趣。如何在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();
            }

2 个答案:

答案 0 :(得分:2)

代替使用

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中第一个元素的值。

答案 1 :(得分:1)

使用循环遍历所有数组长度的方式,仅获取第一个对象的详细信息,如下所示:

try {
  JSONObject jsonObject = new JSONObject(contents);
  JSONArray jsonArray = jsonObject.getJSONArray("stations");

  JSONObject stations = jsonArray.getJSONObject(0);

  String station = stations.getString("station");
  String temperature = stations.getString("temperature");
  String temperature = stations.getString("windchill");

} catch (JSONException e) {
 e.printStackTrace();
 }