我需要Json与Alamofire一起解析的帮助

时间:2019-06-25 14:24:31

标签: json swift parsing alamofire

我是一名初学者程序员,无法解析json文件。我可以在控制台中看到数据,但是我需要帮助来解析json数据。我分享了来自url的json数据,我想与Alamofire进行解析。我用Alamofite和SwiftyJSON安装了PodFile。我没有任何错误,但是我需要帮助来解析它。 我也为以下数据创建了字符串数组。我将数据追加到数组中。

[
  {
    "id" : 1,
    "team" : "Liverpool",
    "players" : [
      {
        "id" : 2,
        "name" : "Alisson",
        "position" : "Goal Keeper",
        "number" : "13"
      },
      {
        "id" : 3,
        "name" : "Salah",
        "position" : "Forward",
        "number" : "10"
      }
    ],
    "trophies" : [
      "2019 champions league",
      "2005 champions league"
    ],
    "logoUrl" : "url"
  },
  {
    "id" : 4,
    "team" : "Real Madrid",
    "players" : [
      {
        "id" : 5,
        "name" : "Ramos",
        "position" : "Defender",
        "number" : "4"
      },
      {
        "id" : 6,
        "name" : "Benzema",
        "position" : "Forward",
        "number" : "9"
      }
    ],
    "trophies" : [
      "2018 champions league",
      "2017 champions league",
      "2016 champions league"
    ],
    "logoUrl" : "url"
  }
]



import Alamofire
import SwiftyJSON

func fetchJsonData(){
       DispatchQueue.main.async {
            Alamofire.request(url).responseData { response in
            guard let data = response.data else { return }
            do {
                let res = try JSONDecoder().decode([PageData].self, from:data)
                print(res)
            } catch  {
                print("having trouble converting it to a dictionary" , error)
            }
        }

        }
}

// this is my modal file

struct PageData: Codable { 
    let team: String
    let players: [Player]
    let trophies: [String]
    let logoUrlL: String 
}

struct Player: Codable {
    let id: Int 
    let name,position, number: String?
}

1 个答案:

答案 0 :(得分:0)

您需要responseData才能使用JSONDecoder

Alamofire.request(url).responseData { response in 
    guard let data = response.data else { return } 
    do { 
        let res = try JSONDecoder().decode([PageData].self, from:data)
        print(res)
    } catch  {
        print("having trouble converting it to a dictionary" , error)
    }
}

playerstrophies都是数组

struct PageData: Codable { 
    let team: String
    let players: [Player]
    let trophies: [String]
    let logoUrlL: String 
}

struct Player: Codable {
    let id: Int 
    let name,position, number, type, quantity: String?
}