安装方法
podfile里面
pod 'HandyJSON'
然后pod install
让模型遵守协议HandyJSON,嵌套模型的子模型也要继承HandyJSON
- 下面代码,只要类遵守HandyJSON协议就可以使用了
- 不需要遵守NSObject也可以使用
我这里继承NSObject是为了重写description变两个打印成员,目的是你print()这个对象的时候就能打印出下面的变量 - mapping 方法用来映射,把解析到的json数据,映射给其他的变量,例如下面把"access_token" 赋值给了temp,把"refresh_token"赋值给了temp2
import HandyJSON
import UIKit
class LoginItem: NSObject,HandyJSON {
@objc var token_type:String = ""
@objc var access_token:String = ""
@objc var expires_in:String = ""
@objc var scope:String = ""
@objc var refresh_token:String = ""
@objc var info = Info()
@objc var temp:String = ""
@objc var temp2:String = ""
required override init(){
}
func mapping(mapper: HelpingMapper) {
mapper <<< self.temp <-- "access_token"
mapper <<< self.temp2 <-- "refresh_token"
}
override var description:String {
return self.dictionaryWithValues(forKeys: ["token_type",
"access_token",
"expires_in",
"scope",
"refresh_token","info","temp","temp2"]).description
}
}
class Info:NSObject,HandyJSON{
@objc var img:String = ""
@objc var name:String = ""
required override init(){
}
override var description:String {
return self.dictionaryWithValues(forKeys: ["img",
"name"
]).description
}
}
解析json数据
使用 deserialize 方法可以把json解析成模型
json数据如下:{
"access_token":"token1234567",
"refresh_token":"r1234567",
"info":{
"img":"1.png",
"name":"zhang san"
}
}
let jsonString = """
{
"access_token":"token1234567",
"refresh_token":"r1234567",
"info":{
"img":"1.png",
"name":"zhang san"
}
}
"""
if let item: LoginItem = LoginItem.deserialize(from: jsonString){
print("item=",item)
}else{
print("解析失败")
}
打印结果:
item= ["info": ["name": zhang san, "img": 1.png], "access_token": token1234567, "token_type": , "refresh_token": r1234567, "expires_in": , "temp2": r1234567, "temp": token1234567, "scope": ]
从json下一个子节点进行解析
例如从上面的info开始解析,然后传给子模型Info
if let item2: Info = Info.deserialize(from: jsonString,designatedPath: "info"){
print("item2=",item2)
}else{
print("解析失败")
}
打印结果:
item2= ["name": zhang san, "img": 1.png]
|