我正在尝试将SwiftyJSON与我的JSON api数据一起使用,但是无法理解转换的工作方式。
以下是SwiftyJSON Git的链接:https://github.com/SwiftyJSON/SwiftyJSON
这是我当前的代码:
.show()
以下是新的SwiftyJSON的示例:
func newFilms() {
let apiKey = "12345"
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)&language=en-US&page=1")
let request = URLRequest(
url: url! as URL,
cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
timeoutInterval: 10 )
let session = URLSession (
configuration: URLSessionConfiguration.default,
delegate: nil,
delegateQueue: OperationQueue.main
)
let task = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let resposeDictionary = try! JSONSerialization.jsonObject(with: data, options:[]) as? [String: Any] {
self.films = (resposeDictionary["results"] as? [String: Any])!
print("response: \(resposeDictionary)")
}
}
self.filteredFilms = self.films
self.filmsCollection.reloadData()
})
task.resume()
}
我的主要问题是,let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
print("\(userName)")
//Now you got your value
}
的内容将如何处理,我很困惑应实现原始代码的哪一部分以及如何将其用于新版本。
答案 0 :(得分:1)
dataFromNetworking
代表从dataTask返回的data
对象。 SwiftyJSON会反序列化。
替换
if let data = dataOrNil {
if let resposeDictionary = try! JSONSerialization.jsonObject(with: data, options:[]) as? [String: Any] {
self.films = (resposeDictionary["results"] as? [String: Any])!
print("response: \(resposeDictionary)")
}
}
与
if let data = dataOrNil {
do {
let json = try JSON(data: data)
self.films = json["results"].dictionaryValue
} catch { print(error) }
}
然而,在Swift 4中,SwiftyJSON
已过时,不再支持强大的内置Codable
协议