在 Swift 中,可以使用 Codable 协议来解析 JSON。但是,当我们要解析一个包含不同类型对象的 JSON 数组时,会遇到一些问题。以下是一个示例 JSON 数据:
[
{
"type": "dog",
"name": "Buddy",
"breed": "Labrador"
},
{
"type": "cat",
"name": "Whiskers",
"age": 3
}
]
上述 JSON 数据包含了两个对象,一个是狗,一个是猫。两个对象拥有不同的属性。我们可以通过以下的方式来解析此类 JSON 数据:
首先,我们要定义一个基类 Animal,如下所示:
class Animal: Decodable {
var type: String
}
接下来,我们定义两个子类,分别表示狗和猫:
class Dog: Animal {
var name: String
var breed: String
}
class Cat: Animal {
var name: String
var age: Int
}
然后,我们可以在代码中使用 JSONDecoder 来解析数据:
let decoder = JSONDecoder()
let animals = try decoder.decode([Animal].self, from: jsonData)
for animal in animals {
switch animal.type {
case "dog":
if let dog = animal as? Dog {
print("This is a dog named \(dog.name) of breed \(dog.breed)")
}
case "cat":
if let cat = animal as? Cat {
print("This is a cat named \(cat.name) and age \(cat.age)")
}
default:
break
}
}
以上例子中,我们定义了一个基类 Animal,并且派生出两个子类:Dog 和 Cat。然后,我们可以使用 JSONDecoder 来将整个 JSON 数组转换成 Animal 类型的数组。最后,我们可以循环遍历数组并根据对象的类型进行判断,最终转化成我们想要的子