ios - 如何从嵌套的 JSON Swift 中检索值
问题描述
所以我一直在 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。有人能指出我正确的方向吗?
解决方案
你可以这样做:
for category in responseJSON.categories {
print(category.categoryName!)
}
或者你可以使用map函数来获取所有categoryName
类似的东西:
let categoryNames = responseJSON.categories.map {$0.categoryName}
推荐阅读
- php - file_get_contents 得到错误的结果
- android - 在 Android 上通过 Unity3D 运行 Google Maps App,立即开始导航
- php - PHP Mail 显示错误“页面不工作”
- port - 无法在谷歌计算引擎中打开端口
- laravel - Laravel - 表单验证仅在某些字段为空时通过
- unity3d - 如何将世界位置转换为 UV 空间?
- css - 第一个元素应占用空闲空间,下一个元素应具有固定大小
- amazon-web-services - 从 AWS lambda 函数读取本地文件
- powershell - Powershell 中的 _Base 属性是什么以及如何使用它们?
- elasticsearch - Digital Ocean 管理的 Kubernetes 卷处于挂起状态