IOS JSON与Object互相解析,ObjectMapper

0 篇文章 0 订阅

目录

一、基本使用:

二、类型转换

三、嵌套对象的映射:


       现在平台与手机交互数据一般都使用xml或json格式,json数据因为格式简单、便于操作、高效率使用偏多。在iOS开发里面,因为是面向对象语言,所以基本以Model处理数据。今天就给大家介绍下swift里面的一个json与model互相转换的类:ObjectMapper

版本:iOS8.0+    swift4

一、基本使用:

ObjectMapper提供了一个协议

public protocol BaseMappable {
	/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
	mutating func mapping(map: Map)
}

public protocol Mappable: BaseMappable {
    /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
    init?(map: Map)
}

只要实现了Mappable就可以实现model和json的相互解析,例子:


struct Student : Mappable{
    var name : String = ""
    var age : Int = 0
    var grade:GradeType = .pass
    
    init?(map: Map) {
    
    }
    
    mutating func mapping(map: Map) {
        name <- map["name"]
        age <- map["age"]
        grade <- map["grade"]
    }
}

enum GradeType : Int{
    case excellent = 0,good,pass,fail //优良中差
    
}

其中<-为objectmapper提供的转换自定义对应符号,支持枚举、常用基本类型

转换方法:

 let json = "{\"name\":\"12\",\"age\":23,\"grade\":0}"
 let student = Mapper<Student>().map(JSONString: json)//json转模型
 let  json3 = Mapper().toJSONString(student!)//模型转son

此外还支持实现Mappable协议的模型、数组、泛型的嵌套使用:

class Course<T:Mappable> : Mappable{
    
    var teacher : Teacher?
    var stus : [Student]?
    var teacherID : String?
    var test : T?
    
    required convenience init?(map: Map) {
        self.init()
    }
    
    func mapping(map: Map) {
        teacher <- map["teacher"]
        stus <- map["stus"]
        teacherID <- map["teacher.id"]
        test <- map["test"]
    }
    
}

其他的还有字典、数组的就不一一举例了。

二、类型转换

有时候平台数据类型需要和业务模型类型不一致,这时候可以直接在实现转换的协议部分处理,不需要单独处置:

 转换方式: grade <- (map["grade"], transform) //在Mapping方法里面右边用元祖表示,右边第一个参数为要解析字段,第二个参数为实现TransformType协议的转换方式实体

TransformOf 为objectMapper实现TransformType协议的一个实体,简单的可以直接调用,例子:

class StudentModel : Mappable{
    
    var id : String = ""
    
    var name : String = ""
    var age : Int = 0
    var grade:GradeType?
    
    private let transform = Transformsss()
    
    required convenience init?(map: Map) {
        self.init()
    }
    
    func mapping(map: Map) {
        name <- map["name"]
        age <- map["age"]
        grade <- (map["grade"], transform)
        id <- map["id"]
//        id <- (map["age"],TransformOf<String,Int>(fromJSON: {String($0 ?? 0)}, toJSON: {Int($0 ?? "0")}))。 //String : 转换结果类型,Int:要转换的类型及json里面类型。fromjson:json数据转成需要数据的方式,toJSON,模型转json的方式
    }

}

class Transformsss : TransformType{
    
    typealias Object = GradeType
    
    typealias JSON = Int
    
    private var val : Int = 0
    init() {
        print("")
    }
    
    func transformFromJSON(_ value: Any?) -> Object?{
        guard let intValue = value as? Int else{
            print("map transform Error file = \(#file),  func = \(#function),   line = \(#line)")
            return nil
        }
        val = intValue
        switch val {
        case 0 ..< 60:
             return .fail
        case 60 ..< 80:
             return .pass
        case 80 ..< 90:
             return .good
        case 90 ..< 100:
             return .excellent
        default:
            return nil
        }
    }
    func transformToJSON(_ value: Object?) -> JSON?{
        return val
    }
}

enum GradeType{
    case excellent,good,pass,fail //优良中差
    
}

调用方式: 

  let json = "{\"name\":\"12\",\"age\":23,\"grade\":87}"
  let model = Mapper<StudentModel>().map(JSONString: json)
  let  json2 = Mapper().toJSONString(model!)

三、嵌套对象的映射:

可以通过点的方式来获取更深层的数据:

teacherID <- map["teacher.id"]   //获取teacher节点下id节点对应的类容

若果本身节点就包含点,为了区分提供了个标记

 teacherID <- map["teacher.id", nested: false] //获取teacher.id节点下的内容

四、其他

后面我将会发布有关objectMapper和Alamofire、Realm的搭配使用。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值