Json转模型2--objectMapple

objectMapple 是一款在Swift下非常好用的数据转模型工具,类似MJExtension

pod引入工程

pod 'ObjectMapper'

import进行声明导入,并创建数据模型

import ObjectMapper

创建数据模型需要遵守Mapple协议和两个协议方法

struct HousesBaseInfo: Mappable {
    init?(map: Map) {
        
    }
    
    mutating func mapping(map: Map) {


    }
}

当然也可以用class来创建模型,如果不需要继承的话,建议直接用struct创建模型

根据数据创建模型

首先来看我们的数据,根据数据我们创建模型

let baseInfo: [String : Any] = ["build_name":"置信·原墅",
                                "build_address":"学院中路与金桥路交汇处东北侧",
                                "area_address":"浙江省温州市鹿城区五马街道",
                                "build_num": 12,
                                "detail_address":["province":"浙江省",
                                                  "city":"温州市"]
struct HousesBaseInfo: Mappable {
    var build_name: String?
    var build_address: String?
    var build_num: Int = 0
    var detail_address: DetailAddressModel?
    
    init?(map: Map) {
        
    }
    mutating func mapping(map: Map) {
        build_name      <- map["build_name"]
        build_address   <- map["build_address"]
        build_num       <- map["build_num"]
        detail_address  <- map["detail_address"]
    }
    var description: String {
        get {
            return Mapper().toJSONString(self, prettyPrint: true)!
        }
    }
}

struct DetailAddressModel: Mappable {
    var province: String?
    var city: String?
    init?(map: Map) {
        
    }
    mutating func mapping(map: Map) {
        province    <- map["province"]
        city        <- map["city"]
    }
}

<-是一个泛型函数,挺形象的
description中的Mapper().toJSONString(self, prettyPrint: true)!是为了方便用来打印出来看看解析结果

使用

// 这样就得到了模型
let basedata: HousesBaseInfo = Mapper().map(JSONObject: self.baseInfo)!
// 打印出来看看
DPrint(message: basedata.description)
/*
{
  "build_name" : "置信·原墅",
  "build_address" : "学院中路与金桥路交汇处东北侧",
  "detail_address" : {
    "city" : "温州市",
    "province" : "浙江省"
  },
  "build_num" : 12
}
*/

注意

使用过程中如果有类型为array最好初始化一个空数组[], 例如

var detail_address: [DetailAddressModel] = []

方便以后用到array属性的时候的转换可选值类型拆包弄得繁琐,还有一些基本类型Int等附上初值,当解析失败得到为nil的时候不会因为强转类型!而崩溃

Mapper().map通过联想可以看到很多构造方法,和返回值类型,常用的有如下,还有很多可以自行选择方法

let model = Mapper().map(JSONObject: ?)
let model = Mapper().map(JSONString: ?)
let model = Mapper().mapArray(JSONObject: ?)
let model = Mapper().mapArray(JSONString: ?)

也可以

let model = DetailAddressModel(JSON:   )
let model = DetailAddressModel(JSONString:   )

你可能感兴趣的:(Json转模型2--objectMapple)