[英]Convert json to string array of arrays in Apple Swift
I am writing my first Swift program (Swift 5.1) using Xcode.我正在使用 Xcode 编写我的第一个 Swift 程序(Swift 5.1)。
I am struggling.我在挣扎。 All I want to do is convert a json string into two arrays of arrays.
我想要做的就是将一个 json 字符串转换为两个数组数组。 A good tutorial is here https://developer.apple.com/swift/blog/?id=37 but it is just too complex.
一个很好的教程在这里https://developer.apple.com/swift/blog/?id=37但它太复杂了。
An example json string is below.下面是一个示例 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"]
}
}
All I want is minimal crappy code that I can paste into a Swift playground to creates two arrays of arrays so in arrayAnimal[0][1] is Minnie, arrayAnimal[2][0] is Dumbo, and arrayMovie[3][1] is Herbie Goes to Monte Carlo for example.我想要的只是最少的蹩脚代码,我可以将其粘贴到 Swift 游乐场中以创建两个数组数组,因此在 arrayAnimal[0][1] 中是 Minnie,arrayAnimal[2][0] 是 Dumbo,而 arrayMovie[3][1] ] 例如赫比去蒙特卡洛。
If it is possible use arrayAnimal["mice"][1] to get Minnie this is perfect, but for now my focus is working out how I should deserialize the json in Swift to get the arrays of arrays.如果可以使用 arrayAnimal["mice"][1] 来获取 Minnie,这是完美的,但现在我的重点是研究如何在 Swift 中反序列化 json 以获取数组数组。
Thank you谢谢
Firstly you need this codable model for your json.首先,您的 json 需要这个可编码模型。 you should add it in separate swift file:
您应该将它添加到单独的 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
}
} }
then you need to convert your string to Data :那么你需要将你的字符串转换为 Data :
let jsonData: Data? = jsonString.data(using: .utf8)
then you can easily decode your data to desired object.然后您可以轻松地将数据解码为所需的对象。
let decoder = JSONDecoder()
do {
let myModel= try decoder.decode(MyModel.self, from: jsonData)
} catch {
print(error.localizedDescription)
}
in the end you can access your desired data through your decoded object.最后,您可以通过解码的对象访问所需的数据。 for example :
例如 :
let anArrayOfStringsOfMices = myModel.animals.mice
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.