1.最简单的json数据转模型
["userName":"jesse","sex":0,"height":0.0]
class PersonModel: NSObject {
var userName = ""
var sex = false
var height = 0.0
init(jsondata: JSON){
userName = jsondata["userName"].stringValue
sex = jsondata["sex"].boolValue
height = jsondata["height"].doubleValue
}
}
//服务器返回的json数据 先转化为JSON 类型
let json = ["userName":"jesse","sex":0,"height":0.0]
let jsonDic = JSON.init(json)
let model = PersonModel(jsondata: jsonDic)
2. json中有数组
[
"userName":"jesse",
"sex":0,
"height":0.0,
"dog":[["name":"二哈","age":1],["name":"比熊","age":3],["name":"泰迪","age":3]
]
class PersonModel: NSObject {
var userName = ""
var sex = false
var height = 0.0
var dogArray = [DogModel]()
init(jsondata: JSON){
userName = jsondata["userName"].stringValue
sex = jsondata["sex"].boolValue
height = jsondata["height"].doubleValue
let dogs = jsondata["dog"].arrayValue
for dic in dogs{
let dicJson = JSON.init(dic)
let dogModel = DogModel.init(jsondata:dicJson)
dogArray.append(dogModel)
}
}
}
class DogModel: NSObject {
var name = ""
var age = 0
init(jsondata: JSON){
name = jsondata["name"].stringValue
age = jsondata["age"].intValue
}
}
//服务器返回的json数据 先转化为JSON 类型
let json = [
"userName":"jesse",
"sex":0,
"height":0.0,
"dog":[ ["name":"二哈","age":1],
["name":"比熊","age":3],
["name":"泰迪","age":3]
]
]
let jsonDic = JSON.init(json)
let model = PersonModel(jsondata: jsonDic)
3. json中有json
[
"userName":"jesse",
"sex":0,
"height":0.0,
"dog":["name":"二哈","age":1]
]
class PersonModel: NSObject {
var userName = ""
var sex = false
var height = 0.0
var dogModel = DogModel.init(jsondata:[:])
init(jsondata: JSON){
userName = jsondata["userName"].stringValue
sex = jsondata["sex"].boolValue
height = jsondata["height"].doubleValue
let dog = jsondata["dog"].dictionaryValue
dogModel = DogModel.init(jsondata:dog)
}
}
class DogModel: NSObject {
var name = ""
var age = 0
init(jsondata: JSON){
name = jsondata["name"].stringValue
age = jsondata["age"].intValue
}
}
//服务器返回的json数据 先转化为JSON 类型
let json = [
"userName":"jesse",
"sex":0,
"height":0.0,
"dog": ["name":"二哈","age":1],
]
let jsonDic = JSON.init(json)
let model = PersonModel(jsondata: jsonDic)
以上三种就是最常用到的json 格式转化为模型的方式,其他复杂的数据结构模式就留给你自己摸索吧