如何从此 JSON 解析中获取子值?

How do I get a sub value from this JSON parse?

我正在尝试从我写的 JSON 中检索特定的子值。 JSON 看起来像这样:

{
    "name":"Tour of Honor Bonus Listing",
    "version":"18.1.3",
    "bonuses": [  
       {  
          "bonusCode":"AZ1",
          "category":"ToH",
          "name":"Anthem Tour of Honor Memorial",
          "value":1,
          "city":"Anthem",
          "state":"AZ",
          "flavor":"Flavor Text Goes Here",
          "imageData":"Base64 Text Goes Here"
      },
      {  
          "bonusCode":"AZ2",
          "category":"ToH",
          "name":"Benson Tour of Honor Memorial",
          "value":1,
          "city":"Benson",
          "state":"AZ",
          "flavor":"Flavor Text Goes Here",
          "imageData":"Base64 Text Goes Here"
      }
    ]
}

在我的 BonusTableViewController.swift 文件中,我在 viewDidLoad 部分使用了以下内容:

let loadedBonuses = loadJson(filename: "BonusData")
print(loadedBonuses as Any)

那个 loadJson 函数看起来像这样:

func loadJson(filename fileName: String) -> [Bonuses]? {
        if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
            do {
                let data = try Data(contentsOf: url)
                let decoder = JSONDecoder()
                let jsonData = try decoder.decode(JSONData.self, from: data)
                print("loadJson loaded JSON")
                return jsonData.bonuses
            } catch {
                print("error:\(error)")
            }
        }
        return nil
    }

JSON 文件名为 BonusData.json,位于应用程序包中。

上面的代码按原样工作,在控制台中我从 JSON 获得了奖金数组的完整输出。但是我想让它只打印 bonusCode 子值。我试过 print(loadedBonuses.bonusCode as Any) 但我收到一条错误消息

Value of type '[BonusTableViewController.Bonuses]?' has no member 'bonusCode'

我尝试了其他变体,但它们都给我同样的错误。如果有帮助,结构如下所示:

// Bonus Data Structs
    struct JSONData: Decodable {
        let name: String
        let version: String
        let bonuses: [Bonuses]
    }
    struct Bonuses: Decodable {
        let bonusCode: String
        let category: String
        let name: String
        let value: Int
        let city: String
        let state: String
        let flavor: String
        let imageData: String
    }

我做错了什么?

错误很明显,[BonusTableViewController.Bonuses]是一个数组(看括号)。

你必须使用循环

for bonus in loadedBonuses! {
    print(bonus.bonusCode)
}

或将值映射到另一个数组

let bonusCodes = loadedBonuses!.map { [=11=].bonusCode }
print(bonusCodes)

注意:do - catch 块没有意义,因为文件在包中并且必须存在。强制展开所有内容。如果代码崩溃,则表明存在设计错误。

func loadJson(filename: String) -> [Bonuses] {
     let url = Bundle.main.url(forResource: fileName, withExtension: "json")!
     let data = try! Data(contentsOf: url)
     let jsonData = try! JSONDecoder().decode(JSONData.self, from: data)
     print("loadJson loaded JSON")
     return jsonData.bonuses
}