arrays - 在 Apple Swift 中将 json 转换为数组的字符串数组

标签 arrays json swift

我正在使用 Xcode 编写我的第一个 Swift 程序 (Swift 5.1)。

我正在挣扎。我想做的就是将 json 字符串转换为两个数组数组。一个很好的教程在这里https://developer.apple.com/swift/blog/?id=37但它太复杂了。

下面是一个 json 字符串示例。

{
  "Animals" :
  {
   "Mice" : ["Mickey", "Minnie"],
   "Ducks" : ["Donald", "Daisy"],
   "Elephants" : ["Dumbo", "Yzma"]
  },
  "Movies" :
  {
   "1940s" : ["Pinocchio", "Fantasia", "Dumbo"],
   "1950s" : ["Cinderella", "Treasure Island", "Peter Pan"],
   "1960s" : ["The Signs of Zorro", "Swiss Family Robinson", "Mary Poppins"],
   "1970s" : ["Herbie Rides Again", "Herbie Goes to Monte Carlo", "Freaky Friday"] 
  }
}

我想要的只是最少的蹩脚代码,我可以将其粘贴到 Swift Playground 中以创建两个数组数组,因此 arrayAnimal[0][1] 中是 Minnie,arrayAnimal[2][0] 中是 Dumbo,而 arrayMovie[3 ][1] 以 Herbie Goes to Monte Carlo 为例。

如果可以的话,使用 arrayAnimal["mice"][1] 来获取 Minnie,这是完美的,但现在我的重点是弄清楚如何在 Swift 中反序列化 json 来获取数组的数组。

谢谢

最佳答案

首先,您的 json 需要这个可编码模型。您应该将其添加到单独的 swift 文件中:

  struct MyModel: Codable {
    let animals: Animals
    let movies: [String: [String]]

    enum CodingKeys: String, CodingKey {
        case Animals
        case Movies
    }
}

// MARK: - Animals
struct Animals: Codable {
    let mice, ducks, elephants: [String]

    enum CodingKeys: String, CodingKey {
        case Mice
        case Ducks
        case Elephants
    }

}

然后您需要将字符串转换为数据:

let jsonData: Data? = jsonString.data(using: .utf8)

然后您可以轻松地将数据解码为所需的对象。

let decoder = JSONDecoder()

do {
    let myModel= try decoder.decode(MyModel.self, from: jsonData)
} catch {
    print(error.localizedDescription)
}

最后你可以通过解码后的对象访问你想要的数据。 例如:

let anArrayOfStringsOfMices = myModel.animals.mice

关于arrays - 在 Apple Swift 中将 json 转换为数组的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59348454/

相关文章:

json - 使用 jq 选择多个字段

javascript - 如何基于 Google Books API 表示和自动完成建议的 JSON?

swift - + 不可用 : Please use explicit type conversions or Strideable methods for mixed-type arithmetics

javascript - 使用 Jquery 比较 JSON 对象数组

python - 将字符串和数字读入数组

c++ - 将二维数组传递给函数会产生奇怪的错误

java - jackson 在python中的替代品是什么?

Swift 模态表 : willPositionSheet does doesn't get called

ios - 表格 View 中是否可能只显示有限的行

python - 对象数组不可picklable