相关链接
https://github.com/kakaopensource/KakaJSON
https://github.com/ibireme/YYModel
https://www.cnblogs.com/mjios/p/11352776.html
1、为什么要混合使用
因为当swift的model如果嵌套使用OC的model时,使用KakaJson无法解析OC的model
2、调研
监听
复制代码Swift
// 有时候可能想在JSON转模型之前、之后做一些额外的操作
// KakaJSON会在JSON转模型之前调用模型的kj_willConvertToModel方法
// KakaJSON会在JSON转模型之后调用模型的kj_didConvertToModel方法
struct Car: Convertible {
var name: String = ""
var age: Int = 0
mutating func kj_willConvertToModel(from json: [String: Any]) {
print("Car - kj_willConvertToModel")
}
mutating func kj_didConvertToModel(from json: [String: Any]) {
print("Car - kj_didConvertToModel")
}
}
let name = "Benz"
let age = 100
let car = ["name": name, "age": age].kj.model(Car.self)
// Car - kj_willConvertToModel
// Car - kj_didConvertToModel
XCTAssert(car.name == name)
XCTAssert(car.age == age)
/*************************************************************/
// 同样也支持类
class Person: Convertible {
var name: String = ""
var age: Int = 0
required init() {}
func kj_willConvertToModel(from json: [String: Any]) {
print("Person - kj_willConvertToModel")
}
func kj_didConvertToModel(from json: [String: Any]) {
print("Person - kj_didConvertToModel")
}
}
class Student: Person {
var score: Int = 0
override func kj_willConvertToModel(from json: [String: Any]) {
// 如果有必要的话,可以调用super的实现
super.kj_willConvertToModel(from: json)
print("Student - kj_willConvertToModel")
}
override func kj_didConvertToModel(from json: [String: Any]) {
// 如果有必要的话,可以调用super的实现
super.kj_didConvertToModel(from: json)
print("Student - kj_didConvertToModel")
}
}
let name = "jack"
let age = 10
let score = 100
let student = ["name": name, "age": age, "score": score].kj.model(Student.self)
// Person - kj_willConvertToModel
// Student - kj_willConvertToModel
// Person - kj_didConvertToModel
// Student - kj_didConvertToModel
XCTAssert(student.name == name)
XCTAssert(student.age == age)
XCTAssert(student.score == score)
3、如何混合使用
故可以使用kj_willConvertToModel来操作混合预处理混合model解析
/// swift model类中嵌套OC的类数据解析
/// - Parameter json: 原始json
func kj_willConvertToModel(from json: [String: Any]) {
if let dic = json["dicKey"] as? [AnyHashable : Any] {
self.feeds = OCModel.yy_model(with: dic)
}
}
4、举一反三
YYModel可以替换为手动解析以及MJExtension,and so on