地址:
https://github.com/haoburongyi/ZHCodable
一個(gè)繼承 Codable 協(xié)議的封裝的字典轉(zhuǎn)模型庫呵扛,使用了 swift 語言風(fēng)格,例如
OC 轉(zhuǎn)模型風(fēng)格
let model = Student.deserialize(jsonString)
Swift 風(fēng)格:
let model = Student.zh.deserialize(json)
只有兩百行代碼筐带,感興趣的可以去下載源碼查看择份,更改 zh 為自定義值,如果對(duì)你有幫助請(qǐng)?jiān)?github 點(diǎn)上 star烫堤,不勝感激
ZHCodable使用方法
json 轉(zhuǎn)模型
let model = Student.zh.deserialize(json)
printLog(model)
模型轉(zhuǎn) json
let modelJSON = model?.zh.toJSONString()
printLog(modelJSON)
json 轉(zhuǎn)字典
let modelDict = modelJSON?.zh.toDict()
printLog(modelDict)
模型轉(zhuǎn)字典
let modelDict1 = model?.zh.toDict()
printLog(modelDict1)
字典轉(zhuǎn)模型
let model1 = Student.zh.deserialize(modelDict!)
printLog(model1)
json 轉(zhuǎn)模型
let model2 = Student.zh.deserialize(modelJSON!)
printLog(model2)
字典轉(zhuǎn)模型
let model3 = Student.zh.deserialize(modelDict1!)
printLog(model3)
Array
數(shù)組轉(zhuǎn) json
let arrayJSON = array.zh.toJSONString()
printLog(arrayJSON)
數(shù)組轉(zhuǎn)元素是字典的數(shù)組 [[String : Any]]
let arrayDicts = array.zh.toDicts()
printLog(arrayDicts)
根據(jù) json 轉(zhuǎn)模型的數(shù)組
let array1 = [Student].zh.deserialize(arrayJSON!)
printLog(array1)
根據(jù)元素是 json 的 array 轉(zhuǎn)模型數(shù)組
let array2 = [Student].zh.deserialize(jsonArray)
printLog(array2)
根據(jù)元素是 json 的 NSArray 轉(zhuǎn)模型數(shù)組
let array3 = [Student].zh.deserialize(jsonDictArray)
printLog(array3)
根據(jù)元素是字典的 array 轉(zhuǎn)模型數(shù)組
let array4 = [Student].zh.deserialize(dictArray)
printLog(array4)
根據(jù)元素是字典的 NSArray 轉(zhuǎn)模型數(shù)組
let array5 = [Student].zh.deserialize(dictNSArray)
printLog(array5)
模型
struct School: ZHCodable {
var name: String? = ""
var address: String? = ""
}
struct Student: ZHCodable {
var name: String?
var age: Int? = 0
var weight: Float? = 0
var school: [School]? = []
}
自定義字段