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

问题描述 投票:-1回答:1

我的目标是获取此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的方式的问题所以我不确定如何继续。

json swift alamofire
1个回答
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) }
© www.soinside.com 2019 - 2024. All rights reserved.