我一直在学习如何在SWIFT应用程序中解析JSON。到目前为止,我一直使用简单的免费API,并没有出现任何问题,应用程序运行得很好。
但是现在我正在调用返回一个数组的API,而且这个数组还嵌套了一个数组。
我已经阅读并准备好了变量来访问指定元素,但是SWIFT仍然看不到这个返回的JSON中的任何数据。我已经苦苦挣扎了两天,尝试了所有可以在线找到和想到的方法,但是我的默认变量仍未被JSON中的数据覆盖。
我使用了SWIFTYJson库。
JSON部分提取:
JSON部分提取:
{
"list" : [
{
"main" : {
"grnd_level" : 984.67999999999995,
"temp_min" : 283.30000000000001,
"temp_max" : 284.54599999999999,
"temp" : 283.30000000000001,
"sea_level" : 1022.5,
"pressure" : 984.67999999999995,
"humidity" : 88,
"temp_kf" : -1.25
},
"clouds" : {
"all" : 0
},
"weather" : [
{
"main" : "Clear",
"icon" : "01n",
"description" : "clear sky",
"id" : 800
}
],
处理它的代码:
func getWeatherData(url: String, parameters: [String : String]){
//make http request and handle the JSON response
print("\(url)\(parameters)")
Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
response in //in means you are inside a closure (function inside a function)
if response.result.isSuccess {
print("Successfully got the weather data!")
let weatherJSON : JSON = JSON(response.result.value!) //saving the JSON response to a constant weathrJSON . We are using ! to self unwrap the value.
self.updateWeatherData(json: weatherJSON) //func to parse our json from API. Self tells the compiler to look for the method inside the current class
print(weatherJSON)
} else {
self.cityName.text = "Unable to fetch weather - please check active connection."
}
}
}
func updateWeatherData(json: JSON) {
(...)
//parse JSON for weather forecast day 1
weatherDataModel.weatherTest1 = json["list"][0]["weather"][0]["id"].intValue
//parse JSON for weather forecast day 2
weatherDataModel.weatherTest2 = json["list"][8]["weather"][0]["id"].intValue
//parse JSON for weather forecast day 3
weatherDataModel.weatherTest3 = json["list"][16]["weather"][0]["id"].intValue
print("TEST variable 1: \(weatherDataModel.weatherTest1)")
print("TEST variable 2: \(weatherDataModel.weatherTest2)")
print("TEST variable 3: \(weatherDataModel.weatherTest3)")
在控制台打印的变量值仍然保持默认值不变:
TEST variable 1: 0
TEST variable 2: 0
TEST variable 3: 0