我正在使用 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/