我一直在学习SWIFT应用程序中的JSON解析。到目前为止,我一直在使用简单的免费API,没有问题,应用程序按设计工作。但是现在我正在调用一个返回数组内部数组的API。我已经按照说明阅读并准备了变量来访问元素,但是SWIFT仍然看不到此返回的JSON中的任何数据。我已经为此苦苦挣扎了2天,更改了所有可以在网上找到和想到的内容,但我的默认变量仍然没有被JSON数据覆盖。使用pod SWIFTYJson。
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
您以错误的方式解析数据。
json["list"]
只是JSON对象而不是数组对象,因此如何通过使用将索引传递给[0]
。
应该按照下面的解决方法进行更正。
weatherDataModel.weatherTest1 = json["list"].arrayValue[0]["weather"].arrayValue[0]["id"].intValue
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句