我有以下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"
}
]
}
}
我怎样才能得到所有城市的名字?
提前谢谢。
答案 0 :(得分:0)
您可以将其视为json对象。请按照以下步骤操作
将其转换为json对象。
然后使用getString()方法将“results”的值转换为一个数组。
答案 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
块。