我想从此JSON URL(https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y)中提取“事件”,“哈斯塔”和“位置” ,但我在努力解决它?谁能帮我?这是我的代码...我想用这3个填充表格视图。
override func viewDidLoad() {
super.viewDidLoad()
splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible
UINavigationBar.appearance().barTintColor = UIColor(red: 52.0/255.0, green: 170.0/255.0, blue: 220.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
let url = NSURL(string:"https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
if error != nil {
print(error)
} else {
if let data = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
if jsonResult!.count > 0 {
if let results = jsonResult!["results"] as? NSDictionary, collection2 = results["collection2"] as? NSArray {
for entry in collection2 {
if let dict = entry["Event"] as? NSDictionary {
print(dict)
}
else if let array = entry as? NSArray {
} else {
}
}
if let items = jsonResult?["Date"] as? NSArray {
print(items)
}
}
}
} catch {
print("In catch block")
}
}
}
}
task.resume()
}
用Swift解析JSON真是太难了。您可以使用SwiftyJSON轻松地做到这一点。
使用您的JSON:
// Get content of json url
let jsonString = try NSString.init(contentsOfURL: url!, encoding: NSUTF8StringEncoding)
// Create JSON object from data
let json = JSON(data: jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
// Check if array for key "collection2" exists
if let collection2 = json["results"]["collection2"].array {
// Create JSON array from it and loop for each object
for (key, subJson):(String, JSON) in JSON(collection2) {
// Check if dictionary for key "Event" exists
if let event = subJson["Event"].dictionary {
print(event)
}
// Check if string for key "Hasta" exists
if let hasta = subJson["Hasta"].string {
print(hasta)
}
// Check if string for key "Location" exists
if let location = subJson["Location"].string {
print(location)
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句