首页 > 解决方案 > 如何从嵌套的 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。有人能指出我正确的方向吗?

标签: iosarraysjsonswiftdictionary

解决方案


你可以这样做:

for category in responseJSON.categories {
     print(category.categoryName!)
}

或者你可以使用map函数来获取所有categoryName类似的东西:

let categoryNames = responseJSON.categories.map {$0.categoryName}

推荐阅读