我正在尝试从Reddit中提取的JSON对象中提取一些数据,并且在使用SwiftyJSON库时遇到问题(您可以在此处找到:https://github.com/SwiftyJSON/SwiftyJSON)。
我在以下网址上拨打Reddit的API," http://www.reddit.com/r/aww/hot.json"我试图从json响应中提取一些键值对,从列表的作者开始。
我的代码如下:
import UIKit
class ViewController: UIViewController, NSURLConnectionDelegate {
var data = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.connectReddit()
}
func connectReddit() {
let urlPath: String = "http://www.reddit.com/r/aww/hot.json"
var url = NSURL(string: urlPath)!
var request = NSURLRequest(URL: url)
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError?
// throwing an error on the line below (can't figure out where the error message is)
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
let json = JSON(data: data)
let authorName = json["data"]["children"]["author"].stringValue
println(authorName)
}
}
你可以看到调用SwifyJSON类的代码,尝试解析数据如下所示,当我清楚地看到那里的数据时,我得到的是nil。
let json = JSON(data: data)
let authorName = json["data"]["children"]["author"].stringValue
println(authorName)
我不确定我在这里做错了什么。
感谢您的帮助!
答案 0 :(得分:2)
你应该试试这个;
let authorName = json["data"]["children"][0]["data"]["author"].stringValue
答案 1 :(得分:0)
对于Swift 3.0.1:
let authorName = json["data"]["children"][0]["data"]["author"].string