gpt4 book ai didi

iOS编程,获取JSON数据

转载 作者:行者123 更新时间:2023-11-29 01:03:05 25 4
gpt4 key购买 nike

我已将 SwiftyJSON.swift 文件添加到我的项目中,并且我正在尝试从网络获取一些数据。现在我的项目运行,但仅直到我尝试从字典中的 json 获取数组的行。我不明白问题出在哪里,但我猜这一定是非常愚蠢的事情,因为我才刚刚开始快速学习。

我只是想在控制台中打印来自该 url 的所有电影的名称,在我设法实现此性能后,我将尝试获取电影的摘要,然后将它们放在 TableView 中。

import UIKit

class FirstViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

//grab the status code and check if the transfer was successful == 200
let requestURL: NSURL = NSURL(string: "https://itunes.apple.com/us/rss/topmovies/limit=50/json")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in

let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode

if (statusCode == 200) {

//sort through the stations key and cast the data into an array of dictionaries
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print("bbbbb")

// From here on, it doesn't print anything anymore
if let movies = json["entry"] as? [[String: AnyObject]] {
print(movies)
print("test")

for movie in movies {

if let name = movie["name"] as? String {
print("mmmm")
print("%@ (Built %@)",name)

}
}

}

}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()

最佳答案

entry是一个json数组,使用.array

if let movies = json["entry"].array {
for movie in movies {
// Do stuff
}
}

也是一般提示。不要强制转换值,例如

movie["something"] as? String

而是使用内置功能:

movie["something"].string

更新

仔细观察您的代码,我发现您根本没有使用 SwiftyJSON.swift。要使用 Swifty,您可以像这样解析 json 文本并获得一个 JSON 对象:

let jsonObj = JSON(data: yourData) // data is a NSData

请再看一下文档:

https://github.com/SwiftyJSON/SwiftyJSON

我想您正在阅读“为什么 Swift 中的典型 JSON 处理不好?”部分。该部分解释了在 Swift 中管理 json 的原生和“坏”方式,真正的文档在下面。

关于iOS编程,获取JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36782028/

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