- swift4 需要在build settings中把swift 3 @objc inference 設置為on
先看一段JSON數(shù)據(jù)扛点,這是網(wǎng)絡返回的數(shù)據(jù)
{
"errorCode": "SUCCESS",
"message": "",
"data": {
"dict": {
"id": 3,
"text": "equweiyu"
},
"list": [{
"headId": 0,
"text": "aaa",
}, {
"headId": 1,
"text": "bbb",
}, {
"headId": 2,
"text": "ccc",
}, ],
"page": 0
}
}
經(jīng)過封裝最后使用的效果
// JSON 數(shù)據(jù)
var json:AnyObject?
//NetDataModel
let netData = json.flatMap(NetDataModel.init)
//[listModel]
let list = (netData?.data?["list"] as? [AnyObject])?.map(listModel.init)
//DataModel
let model = netData?.data.flatMap(DataModel.init)
1. 封裝一個JSON解析基類
使用setValuesForKeysWithDictionary
方法解析跑慕,很簡單
class KVCModel: NSObject {
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override func setValue(value: AnyObject?, forKey key: String) {
super.setValue(value, forKey: key)
}
convenience init(json: [String:AnyObject]?) {
self.init()
json.flatMap(self.setValuesForKeysWithDictionary)
}
convenience init(obj:AnyObject?) {
self.init(json: obj as? [String:AnyObject])
}
}
但是要注意setValuesForKeysWithDictionary
對 Int
不友好 要使用NSNumber
代替
2. 創(chuàng)建Model繼承于基類
class NetDataModel:KVCModel {
var errorCode:String?
var data:AnyObject?
var message:String?
}
class DataModel: KVCModel {
var dict:dictModel?
var list:[listModel]?
var page:NSNumber?
override func setValue(value: AnyObject?, forKey key: String) {
switch key {
case "dict":
self.dict = value.flatMap(dictModel.init)
case "list":
self.list = (value as? [AnyObject])?.map(listModel.init)
default:
super.setValue(value, forKey: key)
}
}
}
class dictModel: KVCModel {
var id:NSNumber?
var text:String?
}
class listModel: KVCModel {
var headId:NSNumber?
var text:String?
}
如果Model的屬性是KVCModel
或者[KVCModel]
就在 setValue(value: AnyObject?, forKey key: String)
解析
3. 使用
解析NetDataModel
:
let netData = json.flatMap(NetDataModel.init)
解析[listModel]
:
let list = (netData?.data?["list"] as? [AnyObject])?.map(listModel.init)
解析DataModel
:
let model = netData?.data.flatMap(DataModel.init)