-
Notifications
You must be signed in to change notification settings - Fork 653
组合与继承
xuyecan edited this page Sep 12, 2017
·
2 revisions
注意,如果Model某个属性不是基本类型
或值为基本类型的集合类型
,那么它必须是一个服从HandyJSON
协议的类型。
如果是泛型集合类型,那么要求泛型实参是基本类型或者服从HandyJSON
协议的类型。
class Component: HandyJSON {
var aInt: Int?
var aString: String?
required init() {}
}
class Composition: HandyJSON {
var aInt: Int?
var comp1: Component?
var comp2: Component?
required init() {}
}
let jsonString = "{\"num\":12345,\"comp1\":{\"aInt\":1,\"aString\":\"aaaaa\"},\"comp2\":{\"aInt\":2,\"aString\":\"bbbbb\"}}"
if let composition = Composition.deserialize(from: jsonString) {
print(composition)
}
如果子类要支持反序列化,那么要求父类也服从HandyJSON
协议。
class Animal: HandyJSON {
var id: Int?
var color: String?
required init() {}
}
class Cat: Animal {
var name: String?
}
let jsonString = "{\"id\":12345,\"color\":\"black\",\"name\":\"cat\"}"
if let cat = Cat.deserialize(from: jsonString) {
print(cat)
}