我的目标是获取此JSON data上最顶级的“browser_download_url”字段,以便我可以使用它在Github上查找应用程序的最新版本。
我目前正在使用带有Alamofire的Swift 4.2来获取网络数据,而使用SwiftyJSON来解析数据。
我开始测试,所以我可以先使用这个simple JSON data。
这是我的代码
Alamofire.request("https://jsonplaceholder.typicode.com/todos").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let test = swiftyJsonVar[0]["title"].string {
print(test)
运行代码会将test
打印为delectus aut autem
,这是正确的JSON数据。
虽然我尝试将代码用于我的原始目标,如下所示
Alamofire.request("https://api.github.com/repos/s0uthwest/futurerestore/releases/latest").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
// print(swiftyJsonVar)
if let test = swiftyJsonVar[0]["assets"]["browser_download_url"].string {
print(test)
虽然运行代码没有任何结果。我确定这是我试图获得browser_download_url
的方式的问题所以我不确定如何继续。
这与Codable
非常简单。
struct
struct Item: Codable {
let userId: Int
let id: Int
let title: String
let completed: Bool
}
let decoder = JSONDecoder()
do {
// don't force unwrap in your project
var yourStructs = try decoder.decode([Item].self, from: data!)
print("yourStructs contains \(String(yourStructs.count)) items")
} catch {
print("kaboom!", error)
}