gpt4 book ai didi

ios - SwiftyJSON 问题

转载 作者:行者123 更新时间:2023-11-28 05:32:36 25 4
gpt4 key购买 nike

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

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

感谢您的帮助!

最佳答案

你应该试试这个;

let authorName = json["data"]["children"][0]["data"]["author"].stringValue

关于ios - SwiftyJSON 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com