Ios Swift和JSON只解析对象而不是数组
我正在开发一个天气应用程序,它解析JSON数据,并将我的标签文本设置为JSON请求的临时值。我从weather对象数组中得到了id的值,但是temp不在数组中,它只是一个对象。有人能告诉我哪里错了吗。我的值重新返回为零,因为我没有正确获取它。这是我的代码片段和JSONIos Swift和JSON只解析对象而不是数组,ios,arrays,json,swift,Ios,Arrays,Json,Swift,我正在开发一个天气应用程序,它解析JSON数据,并将我的标签文本设置为JSON请求的临时值。我从weather对象数组中得到了id的值,但是temp不在数组中,它只是一个对象。有人能告诉我哪里错了吗。我的值重新返回为零,因为我没有正确获取它。这是我的代码片段和JSON @IBAction func getWeather(sender: AnyObject) { let requestURL: NSURL = NSURL(string: "http://api.openweathe
@IBAction func getWeather(sender: AnyObject) {
let requestURL: NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=MYAPPID")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("JSON Downloaded Sucessfully.")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let today = json["weather"] as? [[String: AnyObject]] {
//this is pulling 4 key value pairs
for weather in today {
//this works
let id = weather["id"]?.stringValue
self.trumpDescription.text=id;
print(id)
//this is where I am confused it changes from an array to just an object
let temp = json["temp"] as? String
self.currentTempView.text=temp;
print(temp)
}
}
}
catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}`
以下是JSON:
{
"coord": {
"lon": 138.93,
"lat": 34.97
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04n"
}
],
"base": "cmc stations",
"main": {
"temp": 292.581,
"pressure": 1019.48,
"humidity": 99,
"temp_min": 292.581,
"temp_max": 292.581,
"sea_level": 1028.92,
"grnd_level": 1019.48
},
"wind": {
"speed": 5.36,
"deg": 237.505
},
"clouds": {
"all": 64
},
"dt": 1464964606,
"sys": {
"message": 0.0037,
"country": "JP",
"sunrise": 1464895855,
"sunset": 1464947666
},
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
看起来应该是这样的
if let main = json["main"] as? NSDictionary {
let temp = main["temp"] as! String
print(temp)
}
看起来应该是这样的
if let main = json["main"] as? NSDictionary {
let temp = main["temp"] as! String
print(temp)
}
而不是这个:让temp=json[“temp”]as?字符串
试试这个:
if let main = json["main"] as? [String: AnyObject] {
let temp = main[temp]?.stringValue
print(temp)
//alternatively you can try this as per your convenience of data type
let tempNew = main[temp]?.doubleValue
print(tempNew)
}
而不是这个:让temp=json[“temp”]as?字符串
试试这个:
if let main = json["main"] as? [String: AnyObject] {
let temp = main[temp]?.stringValue
print(temp)
//alternatively you can try this as per your convenience of data type
let tempNew = main[temp]?.doubleValue
print(tempNew)
}
temp
的值位于对象中。天气不好。。。这是一个main对象看看这个,它可能会节省您一些时间。temp
的值在一个对象中。天气不好。。。这是一个主要的目标看看这个,它可能会节省你一些时间。由于你的例子,我现在明白了逻辑。谢谢。由于你的例子,我现在明白了逻辑。非常感谢。