【问题标题】:How to retrieve values from a Nested JSON Swift如何从嵌套的 JSON Swift 中检索值
【发布时间】: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


    【解决方案1】:

    你可以这样做:

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

    或者您可以使用map 函数来获取所有categoryName 之类的:

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

    【讨论】:

      【解决方案2】:

      如果你遍历String,每一项都是字符串的单个字符。


      你可以遍历categories数组

      for category in responseJSON.categories {
          print(category.categoryName ?? "No name")
      }
      

      要获取所有名称,您可以使用 compactMap 从数组中删除 nil

      let names = responseJSON.categories.compactMap { $0.categoryName }
      

      下一步:

      • 如果每个类别都有其名称,则将此属性的类型设为非可选String(然后您可以使用map 代替compactMap

      • 我会改进你的命名。使用 CodingKeys 枚举将 json 的 categoryName 键重命名为 name。那你就可以了

        category.name
        

      【讨论】:

        【解决方案3】:

        就这样。

        response.categories.forEach { print($0.categoryName) }
        

        【讨论】:

        • 感谢您的意见。答案似乎很简单,而我一直在努力解决这个问题,哈哈。
        【解决方案4】:

        如果您想将两个值放在不同的数组中:

        var categoryNameList = [String]
        var excercisesInCategory = [[String]] 
        for category in responseJSON.categories {
            categoryNameList.append(category.categoryName)
            excercisesInCategory.append(category. exercisesInCategory)
        }
        

        【讨论】:

          【解决方案5】:

          这个。

          let categories = responseJSON.categories.map { $0.categoryName }
          categories.forEach { print($0) }
          

          【讨论】:

            【解决方案6】:

            如果您想获取所有categoryNameexercisesInCategory 格式的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)
                        let response = try JSONDecoder().decode(Response.self, from: data)
            
                        for category in response.categories {
                            print("Category Name: \(category.categoryName!)")
            
                            for exercises in category.exercisesInCategory {
                                print("Exercise in category: \(exercises)")
                            }
                        }
                    } catch {
                        print(error)
                    }
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-08-01
              • 1970-01-01
              • 1970-01-01
              • 2016-05-07
              • 1970-01-01
              相关资源
              最近更新 更多