繁体   English   中英

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

[英]Convert json to string array of arrays in Apple 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 游乐场中以创建两个数组数组,因此在 arrayAnimal[0][1] 中是 Minnie,arrayAnimal[2][0] 是 Dumbo,而 arrayMovie[3][1] ] 例如赫比去蒙特卡洛。

如果可以使用 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
    }

}

那么你需要将你的字符串转换为 Data :

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM