【发布时间】:2014-11-26 01:12:41
【问题描述】:
我正在尝试从我从 Reddit 中提取的 JSON 对象中提取一些数据,并且在使用 SwiftyJSON 库时遇到了问题(您可以在此处找到:https://github.com/SwiftyJSON/SwiftyJSON)。
我在以下 URL 调用 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)
我不确定我在这里做错了什么。
感谢您的帮助!
【问题讨论】:
-
如果您查看该 URL 返回的 json,您应该注意到 json["data"]["children"] 将是一个对象数组,而不是包含“作者”的对象。
标签: ios json swift swifty-json