【问题标题】:Convert json to string array of arrays in Apple Swift在Apple Swift中将json转换为数组的字符串数组
【发布时间】:2019-12-15 22:02:56
【问题描述】:

我正在使用 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] 例如 Herbie Goes to Monte Carlo。

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

谢谢

【问题讨论】:

  • 这应该会有所帮助,quicktype.io。将该 JSON 转储到编辑器中,从语言选择器中选择 swift,然后为您完成所有艰苦的工作。

标签: arrays json swift


【解决方案1】:

首先,您的 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

【讨论】:

  • 有效!谢谢,很简单,但如果留给我自己的设备,我仍然会继续努力
  • @Steve 很高兴听到。很高兴检查我的答案并投票赞成:)
猜你喜欢
  • 1970-01-01
  • 2016-07-13
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2016-01-27
  • 2015-04-16
相关资源
最近更新 更多