有如下json数据
[{
"id": 9,
"code": "100000",
"name": "北京市",
"baiduCode": "131",
"gaodeCode": "",
"tengxunCode": "",
"parentId": 8,
"level": 2,
"areas": [{
"id": 10,
"code": "100020",
"name": "朝阳区",
"baiduCode": "",
"gaodeCode": "",
"tengxunCode": "",
"parentId": 9,
"level": 3,
"areas": null
}, {
"id": 13,
"code": "100089",
"name": "海淀区",
"baiduCode": null,
"gaodeCode": null,
"tengxunCode": null,
"parentId": 9,
"level": 3,
"areas": null
}]
}, {
"id": 12,
"code": "300000",
"name": "天津市",
"baiduCode": null,
"gaodeCode": null,
"tengxunCode": null,
"parentId": 11,
"level": 2,
"areas": null
}]
模型定义如下
import YYModel
@objcMembers // 一定要加这个,不然解析为空数据
class CityListModel: NSObject, NSCoding, YYModel {
var areas: [CityListModel]?
var baiduCode: String?
var code: String = ""
var gaodeCode: String = ""
var ids: Int = 0
var level: Int = 0
var name: String = ""
var parentId: Int = 0
var tengxunCode: String = ""
override init() {
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
self.init()
self.yy_modelInit(with: aDecoder)
}
func encode(with aCoder: NSCoder) {
self.yy_modelEncode(with: aCoder)
}
static func modelCustomPropertyMapper() -> [String : Any]? {
return ["ids": "id"]
}
static func modelContainerPropertyGenericClass() -> [String : Any]? {
// return ["areas": CityListModel.classForCoder()]
return ["areas": CityListModel.self]
}
override var description: String {
// return dictionaryWithValues(forKeys: ["code", "name"]).description // 打印指定字段
return yy_modelDescription()
}
class func getSavePath() -> String {
let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
let path = (docPath as String) + "/cityList.plist"
print(path)
return path
}
class func saveCityModel(cityArr:[CityListModel]) {
let path = getSavePath()
NSKeyedArchiver.archiveRootObject(cityArr, toFile: path)
}
class func getCityModelFromDie() -> [CityListModel] {
let cityModel = NSKeyedUnarchiver.unarchiveObject(withFile: getSavePath())
return cityModel as! [CityListModel]
}
}
使用
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let path = Bundle.main.path(forResource: "search", ofType: "json")!
let str = try? String(contentsOfFile: path) as! String
let cityArr = NSArray.yy_modelArray(with: CityListModel.self, json: str) as! [CityListModel]
CityListModel.saveCityModel(cityArr: cityArr)
sleep(2)
print(CityListModel.getCityModelFromDie())
}