Swift json轉(zhuǎn)模型秃殉,HandyJson已經(jīng)不建議使用了姥份,一般采用Codable树埠,代碼如下
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
try JSONDecoder().decode(modelType, from: jsonData)
但是swift對(duì)于json對(duì)象是有要求的,如果不符合要求疾呻,JSONSerialization.data會(huì)直接崩潰除嘹,貼一下蘋(píng)果的注釋
A class for converting JSON to Foundation objects and converting Foundation objects to JSON.
An object that may be converted to JSON must have the following properties:
- Top level object is an NSArray or NSDictionary
- All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
- All dictionary keys are NSStrings
- NSNumbers are not NaN or infinity
解決方案1:解析前先驗(yàn)證json對(duì)象的有效性,
如果傳入null對(duì)象岸蜗,就過(guò)不了校驗(yàn)
如果傳入的是jsonObject尉咕,內(nèi)部含有null對(duì)象,那是可以通過(guò)校驗(yàn)的璃岳,使用Codable進(jìn)行json轉(zhuǎn)模型時(shí)年缎,如果該屬性為可選值悔捶,則屬性賦值為nil,如果該屬性為不可選值单芜,會(huì)報(bào)錯(cuò)
guard JSONSerialization.isValidJSONObject(jsonObject) == true else {
imiLogE("不合法的jsonObject,請(qǐng)檢查!!!")
return nil
}
解決方案2:去除json對(duì)象中的NSNull對(duì)象
/// 將JsonObject(字典或數(shù)組)中的null元素替換為空字符串,可以用來(lái)避免轉(zhuǎn)模型時(shí)的一些異常
/// - Parameter jsonObject: Array或者Dictionary,其他類(lèi)型會(huì)返回傳入的對(duì)象
/// - Returns: 不帶null的對(duì)象
public static func handleJsonObjectNullValue(_ jsonObject: Any) -> Any {
if let jsonArray = jsonObject as? Array<Any> {
let noNullArray: [Any] = jsonArray.map { value in
if value is NSNull {
return ""
}else if let value = value as? Array<Any> {
return handleJsonObjectNullValue(value)
}else if let value = value as? Dictionary<AnyHashable, Any> {
return handleJsonObjectNullValue(value)
}else {
return value
}
}
return noNullArray
}else if let jsonDic = jsonObject as? Dictionary<AnyHashable, Any> {
let noNullDic: [AnyHashable: Any] = jsonDic.mapValues { value in
if value is NSNull {
return ""
}else if let value = value as? Array<Any> {
return handleJsonObjectNullValue(value)
}else if let value = value as? Dictionary<AnyHashable, Any> {
return handleJsonObjectNullValue(value)
}else {
return value
}
}
return noNullDic
}
return jsonObject
}