Swift 字典转模型(KakaJSON) ---4.动态模型

有时候服务器返回的某个字段的内容类型可能是不确定的

  • 当时给出的解决方案是实现kj_modelValue或者kj_didConvertToModel方法,根据实际需求自定义JSON的解析逻辑
  • 如果不确定的内容是要转成模型,KakaJSON有更简单的实现方案

1.举例

struct Book: Convertible {
    var name: String = ""
    var price: Double = 0.0
}

struct Car: Convertible {
    var name: String = ""
    var price: Double = 0.0
}

struct Pig: Convertible {
    var name: String = ""
    var height: Double = 0.0
}

struct Dog: Convertible {
    var name: String = ""
    var weight: Double = 0.0
}

struct Person: Convertible {
    var name: String = ""
    var pet: Any?
    
    // 这里用`NSArray`、`NSMutableArray`也行
    var toys: [Any]?
    
    // 这里用`NSDictionary`、`NSMutableDictionary`也行
    var foods: [String: Any]?
    
    func kj_modelType(from jsonValue: Any?, _ property: Property) -> Convertible.Type? {
        switch property.name {
        case "toys": return Car.self  // `toys`数组存放`Car`模型
        case "foods": return Book.self  // `foods`字典存放`Book`模型
        case "pet":
            if let pet = jsonValue as? [String: Any], let _ = pet["height"] {
                // 如果`pet`属性的`jsonValue`是个字典,并且有`height`这个key,就转为`Pig`模型
                return Pig.self
            }
            // 将`jsonValue`转为`Dog`模型赋值给`pet`属性
            return Dog.self
        default: return nil
        }
    }
    
}

// 测试数据
let name = "Jack"
let dog = (name: "Wang", weight: 109.5)
let pig = (name: "Keke", height: 1.55)
let books = [
    (name: "Fast C++", price: 666.0),
    (name: "Data Structure And Algorithm", price: 1666.0)
]
let cars = [
    (name: "Benz", price: 100.5),
    (name: "Bently", price: 300.6)
]

// JSON数据
let json: [String: Any] = [
    "name": name,
    "pet": ["name": dog.name, "weight": dog.weight],
    // "pet": ["name": pig.name, "height": pig.height],
    "toys": [
        ["name": cars[0].name, "price": cars[0].price],
        ["name": cars[1].name, "price": cars[1].price]
    ],
    "foods": [
        "food0": ["name": books[0].name, "price": books[0].price],
        "food1": ["name": books[1].name, "price": books[1].price]
    ]
]

let person = json.kj.model(Person.self)

print("name:\(person.name) pet:\(person.pet!)")

guard let toys = person.toys, let foods = person.foods  else {
    return
}
for car: Car in toys as! [Car] {
    print("car:\(car.name)  \(car.price)")
}
for (key, value) in foods {
    print("key:\(key)  value:\(value)")
}
/*
name:Jack pet:Dog(name: "Wang", weight: 109.5)
car:Benz  100.5
car:Bently  300.6
key:food0  value:Book(name: "Fast C++", price: 666.0)
key:food1  value:Book(name: "Data Structure And Algorithm", price: 1666.0)
*/

Swift 字典转模型(KakaJSON) ---1.基本用法
Swift 字典转模型(KakaJSON) ---2.数据类型
Swift 字典转模型(KakaJSON) ---3.key处理
Swift KakaJSON 05.---模型转字典
Swift KakaJSON 06.---Coding/归档/解档

你可能感兴趣的:(Swift 字典转模型(KakaJSON) ---4.动态模型)