从嵌套的JSON结果中获取JSON对象

时间:2015-02-11 22:19:54

标签: java android json nested

我有以下JSON结果:
这是天气结果 我的目标是首先获得城市名称 然后根据列表中的一个城市,请求一个属性

{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "hourly": 1
  ,
  "lang": 1
  }
        , "results": [
        {
        "name": "Al-Arz",
        "city": "Al-Arz",
        "state": "",
        "country": "LB",
        "country_iso3166":"LB",
        "country_name":"Lebanon",
        "zmw": "00000.1.40105",
        "l": "/q/zmw:00000.1.40105"
        }
        ,
        {
        "name": "Beirut",
        "city": "Beirut",
        "state": "",
        "country": "LB",
        "country_iso3166":"LB",
        "country_name":"Lebanon",
        "zmw": "00000.1.40100",
        "l": "/q/zmw:00000.1.40100"
        }
        ,
        {
        "name": "Dahr Baidar",
        "city": "Dahr Baidar",
        "state": "",
        "country": "LB",
        "country_iso3166":"LB",
        "country_name":"Lebanon",
        "zmw": "00000.1.40110",
        "l": "/q/zmw:00000.1.40110"
        }
        ,
        {
        "name": "Houche-Al-Oumara",
        "city": "Houche-Al-Oumara",
        "state": "",
        "country": "LB",
        "country_iso3166":"LB",
        "country_name":"Lebanon",
        "zmw": "00000.1.40101",
        "l": "/q/zmw:00000.1.40101"
        }
        ,
        {
        "name": "Merdjayoun",
        "city": "Merdjayoun",
        "state": "",
        "country": "LB",
        "country_iso3166":"LB",
        "country_name":"Lebanon",
        "zmw": "00000.1.40104",
        "l": "/q/zmw:00000.1.40104"
        }
        ,
        {
        "name": "Rayack",
        "city": "Rayack",
        "state": "",
        "country": "LB",
        "country_iso3166":"LB",
        "country_name":"Lebanon",
        "zmw": "00000.1.40102",
        "l": "/q/zmw:00000.1.40102"
        }
        ,
        {
        "name": "Tripoli",
        "city": "Tripoli",
        "state": "",
        "country": "LB",
        "country_iso3166":"LB",
        "country_name":"Lebanon",
        "zmw": "00000.1.40103",
        "l": "/q/zmw:00000.1.40103"
        }
        ]
    }
}

我怎样才能得到所有城市的名字?
提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以将其视为json对象。请按照以下步骤操作

  1. 将其转换为json对象。

  2. 然后使用getString()方法将“results”的值转换为一个数组。

  3. 然后将此结果转换为json数组。
  4. 然后使用getString方法逐个遍历json数组广告,您可以获取所有城市的值。

答案 1 :(得分:0)

JSONObject rootObject = (JSONObject)new JSONTokener(yourJsonString).nextValue();
JSONObject responseObject = rootObject.getJSONObject("response");
JSONArray cityArray = responseObject.getJSONArray("results");
List<String> listWithCityNames = new ArrayList<String>();

for(int i = 0; i< cityArray.lenght();i++){
  listWithCityNames.add(cityArray.getJSONObject(i).getString("name"));

 }

for(String city:listWithCityNames){
   System.out.println(city);
 }

此代码段解析var yourJsonString中的json字符串,并在json的name对象内的results数组中收集属性response。如果需要,添加Try/Catch块。