我正在尝试从我写的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获得了bonuses数组的完整输出。但是我希望它只打印bonusCode子值。我试过了print(loadedBonuses.bonusCode as Any)
,但我收到了一条错误说明,
类型'[BonusTableViewController.Bonuses]的值?'没有会员 'bonusCode'
我尝试了其他变种,但它们都给了我同样的错误。如果有帮助,Struct看起来像这样:
// 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
}
我做错了什么?
答案 0 :(得分:0)
错误很明显,[BonusTableViewController.Bonuses]
是一个数组(见括号)。
你必须使用循环
for bonus in loadedBonuses! {
print(bonus.bonusCode)
}
或将值映射到另一个数组
let bonusCodes = loadedBonuses!.map { $0.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
}