【发布时间】:2019-08-09 17:49:45
【问题描述】:
所以我一直在使用 Swift 中的嵌套 JSON 文件(我在本地添加到我的项目中)。我在下面包含了我正在处理的 JSON 文件的一部分。数据结构如下:
{
"categories": [
{
"categoryName": "Albatrosses",
"exercisesInCategory": [
"Wandering albatross",
"Grey-headed albatross",
"Black-browed albatross",
"Sooty albatross",
"Light-mantled albatross"
]
},
{
"categoryName": "Cormorants",
"exercisesInCategory": [
"Antarctic shag",
"Imperial shag",
"Crozet shag"
]
},
{
"categoryName": "Diving petrels",
"exercisesInCategory": [
"South Georgia diving petrel",
"Common diving petrel"
]
},
{
"categoryName": "Ducks, geese and swans",
"exercisesInCategory": [
"Yellow-billed pintail"
]
}
]
}
为了检索数据,我创建了 2 个结构来表示 JSON 中的数据,这样我就可以从中检索值。它们如下:
struct Response:Codable{
let categories: [Categories]
}
struct Categories:Codable{
let categoryName : String?
let exercisesInCategory : [String]
}
文件名为fitnessData.json,我正在尝试使用以下代码从中检索数据:
private func parse(){
print("Retrieving JSON Data...")
if let url = Bundle.main.url(forResource: "fitnessData", withExtension: "json") {
do {
let data = try Data(contentsOf: url)
self.response = try JSONDecoder().decode(Response.self, from: data)
if let responseJSON = self.response {
print("The categories are: ", responseJSON.categories[1].categoryName!)
}
} catch {
print(error)
}
}
}
问题是我想从 JSON 文件中检索所有“categoryName”值,以及所有“exercisesInCategory”值。但到目前为止,我只设法导航到 JSON 文件中的特定项目并检索该项目,即
responseJSON.categories[1].categoryName!
例如,我想遍历 JSON 文件以获取所有“categoryName”值。但是为了做到这一点,我必须写这样的东西:
for value in responseJSON.categories[1].categoryName! {
print(value)
}
其中“1”表示类别结构的所有值。上面的代码显然只会打印 JSON 文件中 categories 数组中第二个索引的 categoryName。有人能指出我正确的方向吗?
【问题讨论】:
标签: ios arrays json swift dictionary