我如何使用 SwiftyJSON 读取数组中的 JSON 数据?

How would I read JSON data in an array using SwiftyJSON?

我刚刚被介绍在我的 iOS 应用程序中使用 JSON 数据。我使用了一项服务来解析来自网站的 JSON 数据,我想解码该数据以在 UITableView 中显示给我的用户。我的 JSON 数据如下所示:

{
  "success": true,
  "outputScenario": "Default",
  "data": {
    "collection": [
      {
        "teamName": "Gulf Coast Monarchs, FL",
        "teamW": "10",
        "teamL": "0",
        "teamT": "0",
        "teamPct": "1.000",
        "teamGB": "-",
        "teamGP": "10",
        "teamRA": "10",
        "teamDivision": "10-0-0"
      },
      {
        "teamName": "Ohio Nationals, OH",
        "teamW": "9",
        "teamL": "1",
        "teamT": "0",
        "teamPct": ".900",
        "teamGB": "1.0",
        "teamGP": "10",
        "teamRA": "20",
        "teamDivision": "9-1-0"
      },      {
        "teamName": "Mount Kisco Chiefs, NY",
        "teamW": "0",
        "teamL": "8",
        "teamT": "0",
        "teamPct": ".000",
        "teamGB": "8.0",
        "teamGP": "8",
        "teamRA": "108",
        "teamDivision": "0-8-0"
      }
      {
        "teamName": "Mount Kisco Chiefs, NY",
        "teamW": "0",
        "teamL": "8",
        "teamT": "0",
        "teamPct": ".000",
        "teamGB": "8.0",
        "teamGP": "8",
        "teamRA": "108",
        "teamDivision": "0-8-0"
      }
    ]
  },

请记住,我已经删除了 JSON 中提供的大量数据,因此很容易查看。

如果可能的话,我想使用 SwiftyJSON 解码此数据,以便我可以在 UITableView 中将其显示给我的用户。现在,UITableView 将在 UITableView.textLabel.text 中显示 team name,在 UITableView.detailTextLabel.text 中显示 teamWteamL。我将如何使用 SwiftyJSON 解码这些数据?我正在努力弄清楚如何解码这种类型的结构。我想使用我创建的模型:

struct Standing: Decodable {

var teamName: String
var teamW: Int
var teamL: Int
var teamT: Int
var teamPct: Int
teamGB: Int
teamGP: Int
teamRA: Int
teamDivision: String

}

如果您使用 Decodable,则根本不需要使用 SwiftyJSON,所有内容都内置于 Swift 本身。

将其用作您的模型结构:

struct Standing: Codable {
    let success: Bool
    let outputScenario: String
    let data: DataClass
}

struct DataClass: Codable {
    let collection: [Collection]
}

struct Collection: Codable {
    let teamName, teamW, teamL, teamT: String
    let teamPct, teamGB, teamGP, teamRA: String
    let teamDivision: String
}

并像这样解析它:

do {
  let standing = try JSONDecoder().decode(Standing.self, from: data)
} catch {
  print(error)
}

你为什么要使用 SwiftyJSON 因为你已经采用了 Decodable

您的结构中的类型大错特错,因为所有值都是 String。您还需要两个其他结构作为父对象。

struct Root: Decodable {
    let success : Bool
    let outputScenario : String
    let data : TeamData
}

struct TeamData: Decodable {
    let collection : [Standing]
}

struct Standing: Decodable {
    let teamName, teamW, teamL, teamT: String
    let teamPct, teamGB, teamGP, teamRA: String
    let teamDivision: String
}

解码数据,Standing数组在变量standings.

do {
    let result = try JSONDecoder().decode(Root.self, from: data)
    let standings = result.data.collection
} catch {
    print(error)
}