我在这里使用一些JSON代码。这种解析格式仅返回字典。我需要解析我的数组; [{“id”:“1”,“Venue_Name”:“Fashon Show”}]。如何使用这种格式解析数组中的字典而不仅仅是字典?
let urlAsString = "http://date.jsontest.com"
let url: NSURL = NSURL(string: urlAsString)
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
// 3
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
// 4
let jsonDate: String! = jsonResult["date"] as NSString
let jsonTime: String! = jsonResult["time"] as NSString
dispatch_async(dispatch_get_main_queue(), {
self.dateLabel.text = jsonDate
self.timeLabel.text = jsonTime
})
})
// 5
jsonQuery.resume()
}
答案 0 :(得分:0)
这比我想象的要容易......
刚刚将jsonResult更改为数组,
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSArray
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
并将此代码中的jsonResult更改为[0]
let jsonDate: String! = jsonResult[0]["date"] as NSString