使用OC开发时,JSON解析方法很多,如可以自己解析,也可以使用JsonModel,MJExtension等第三方,切换到Swift开发后,也还可以通过桥接的方式调用OC的,但这样会略显麻烦,Swift上也提供了直接进行json解析的方案,目前主流的有SwiftyJSON,ObjectMapper,HandyJson,以及swift 4上对JSON解析的原生支持。下面将一一介绍
一.SwiftyJSON
class Animal { var name: String? var age: Int? } func swiftyJson(){ let jsonStr = "{"name":"哈士奇","age":2}" if let jsonData = jsonStr.data(using: .utf8){ let json = JSON(jsonData) let name = json["name"].stringValue let age = json["age"].intValue let animal = Animal() animal.name = name animal.age = age print("swiftyJson: name: (name),age: (age)") } }
这种解析结构明确,模型转换需要手动编码
二.ObjectMapper
class Animal: Mappable { var name: String? var age: Int? required init?(map: Map){ } func mapping(map: Map) { name <- map["name"] age <- map["age"] } } func objectMapper(){ let jsonStr = "{"name":"哈士奇","age":2}" let animal = Mapper<Animal>().map(JSONString: jsonStr) let name = animal?.name! let age = animal?.age! print("swiftyJson: name: (name!),age: (age!)") let JSONString = user?.toJSONString() print(JSONString!) }
ObjectMapper模型转换需要手动编码
三.HandyJSON
class Animal: HandyJSON { var name: String? var age: Int? required init() {} } func handyJSON(){ let jsonStr = "{"name":"哈士奇","age":2}" if let animal = Animal.deserialize(from: jsonStr) { let name = animal.name! let age = animal.age! print("handyJSON: name: (name),age: (age)") } }
使用HandyJson需要继承HandyJSON,不需要手动编码就可以完成模型转换,比较简单。
四. 原生JSON解析,Encoder/Decoder
class Bank: Codable { var name: String? var address: String? } class Teacher: Codable { var school: String? var banks: Array<Bank>? } func nativeJson(){ let jsonStr = "{"banks":[{"name":"中国银行","address":"北京市朝阳区XXX"},{"name":"中国农业银行","address":"北京市海淀区XXX"}],"school":"北京四中"}" let jsonData = jsonStr.data(using: .utf8) let decoder = JSONDecoder() do { let animal = try decoder.decode(Teacher.self, from: jsonData!) let school = animal.school! print("nativeJson: name: (school)") for bank in animal.banks! { print("nativeJson: name: (bank.name!),address: (bank.address!)") } } catch { // 异常处理 } }
系统原生的解析也可以进行模型转换,结果如下
通过对上面四种解析方式的比较,3,4种比较符合我们平时开发的需求,都可以进行模型转换,同时对三,四进行性能分析,执行解析1万次,系统原生的性能稍好
方法耗时为:1.1795408710022457
方法耗时为:0.37943107699538814
所以在实际的开发中,可以根据项目情况优先选择系统原生的jSON解析,前提是在Swift 4以上才支持。