【发布时间】:2014-08-02 19:43:40
【问题描述】:
我可以通过代码中的链接访问 Yahoo Finance 数据集。它在调试窗口中执行并打印 JSON 数据。我将如何存储并打印 myNameLabel 中的选定字段。例如“symbol”或“LastTradePriceOnly”字段?
class ViewController: UIViewController {
@IBOutlet weak var myNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let manager = AFHTTPRequestOperationManager()
manager.GET( "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22AAPL%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
println("JSON: " + responseObject.description)
//How to access and print individual fields?
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
【问题讨论】:
-
使用
NSJSONSerialization类反序列化,这将产生一个取决于顶部 JSON 元素的数组或字典。然后使用标准 Swift 语法访问数组或字典中的值。 -
看看 AFN 的 Swift 兄弟 - Alamofire。 :)
-
@Zaph 仅供参考,
responseObject已经反序列化。
标签: json swift afnetworking-2