如何使用Alamofire和SwiftyJSON正确解析JSON

时间:2019-02-16 13:18:45

标签: json swift alamofire

我的目标是在此JSON data上获得最顶部的“ browser_download_url”字段,以便我可以使用它在Github上找到应用程序的最新版本。

我目前正在使用Swift 4.2和Alamofire来获取网络数据,并使用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的方式存在问题,所以我不确定如何进行。

1 个答案:

答案 0 :(得分:0)

Codable非常简单。

  1. 创建一个struct

    struct Item: Codable {
        let userId: Int
        let id: Int
        let title: String
        let completed: Bool
    }
    
  2. 在Alamofire完成处理程序中,您只需对其进行解码,如下所示:

    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)
    }
    
相关问题