https://www.jianshu.com/p/25db8030dba2
2018.05.02 20:20:16字數 1,493閱讀 5,017
一 簡介
二 特性
三 安裝使用以及封裝
四 使用示例
五 總結
一 簡介
HandyJSON是一個用於Swift語言中的JSON序列化/反序列化庫。
與其他流行的Swift JSON庫相比,HandyJSON的特點是,它支持純swift類,使用也簡單。它反序列化時(把JSON轉換為Model)不要求Model從NSObject繼承(因為它不是基於KVC機制),也不要求你為Model定義一個Mapping函數。只要你定義好Model類,聲明它服從HandyJSON協議,HandyJSON就能自行以各個屬性的屬性名為Key,從JSON串中解析值。
HandyJSON目前依賴於從Swift Runtime源碼中推斷的內存規則,任何變動我們將隨時跟進。
二 特性
-
序列化Model到JSON、從JSON反序列化到Model
-
自然地以Model的屬性名稱作為解析JSON的Key,不需要額外指定
-
支持Swift中大部分類型
-
支持class、struct定義的Model
-
支持自定義解析規則
-
類型自適應,如JSON中是一個Int,但對應Model是String字段,會自動完成轉化
三 安裝使用以及封裝
3.1 安裝
我使用的是cocopod進行包引入管理,修改Prodfie文件,添加如下代碼:
pod 'HandyJSON', '~> 4.1.1'
官方說明(swift3.0用大於1.8.0版本的 swift4.0用4.1.1):
To use with Swift 3.x using >= 1.8.0 To use with Swift 4.0 using == 4.1.1
實際使用過程中,1.8.0是有問題的,有個必現的bug,建議直接用4.1.1版本的,4.1如果安裝失敗,請更新你的cocopod到最新版
3.2 封裝
為了方便我們項目中的使用,我們一般都會在做一層封裝,方便庫的以后升級替換,以及方便日常業務邏輯的處理
JsonUtil.swift import UIKit import HandyJSON class JsonUtil: NSObject { /** * Json轉對象 */ static func jsonToModel(_ jsonStr:String,_ modelType:HandyJSON.Type) ->BaseModel { if jsonStr == "" || jsonStr.count == 0 { #if DEBUG print("jsonoModel:字符串為空") #endif return BaseModel() } return modelType.deserialize(from: jsonStr) as! BaseModel } /** * Json轉數組對象 */ static func jsonArrayToModel(_ jsonArrayStr:String, _ modelType:HandyJSON.Type) ->[BaseModel] { if jsonArrayStr == "" || jsonArrayStr.count == 0 { #if DEBUG print("jsonToModelArray:字符串為空") #endif return [] } var modelArray:[BaseModel] = [] let data = jsonArrayStr.data(using: String.Encoding.utf8) let peoplesArray = try! JSONSerialization.jsonObject(with:data!, options: JSONSerialization.ReadingOptions()) as? [AnyObject] for people in peoplesArray! { modelArray.append(dictionaryToModel(people as! [String : Any], modelType)) } return modelArray } /** * 字典轉對象 */ static func dictionaryToModel(_ dictionStr:[String:Any],_ modelType:HandyJSON.Type) -> BaseModel { if dictionStr.count == 0 { #if DEBUG print("dictionaryToModel:字符串為空") #endif return BaseModel() } return modelType.deserialize(from: dictionStr) as! BaseModel } /** * 對象轉JSON */ static func modelToJson(_ model:BaseModel?) -> String { if model == nil { #if DEBUG print("modelToJson:model為空") #endif return "" } return (model?.toJSONString(