1

我正在尝试从我从 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)

我不确定我在这里做错了什么。

谢谢您的帮助!

4

2 回答 2

2

你应该试试这个;

let authorName = json["data"]["children"][0]["data"]["author"].stringValue
于 2015-02-10T14:02:45.107 回答
0

对于 Swift 3.0.1:

let authorName = json["data"]["children"][0]["data"]["author"].string
于 2016-11-11T01:26:50.003 回答