Swift json转模型,HandyJson已经不建议使用了,一般采用Codable,代码如下
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
try JSONDecoder().decode(modelType, from: jsonData)
但是swift对于json对象是有要求的,如果不符合要求,JSONSerialization.data会直接崩溃,贴一下苹果的注释
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:解析前先验证json对象的有效性,
如果传入null对象,就过不了校验
如果传入的是jsonObject,内部含有null对象,那是可以通过校验的,使用Codable进行json转模型时,如果该属性为可选值,则属性赋值为nil,如果该属性为不可选值,会报错
guard JSONSerialization.isValidJSONObject(jsonObject) == true else {
imiLogE("不合法的jsonObject,请检查!!!")
return nil
}
解决方案2:去除json对象中的NSNull对象
/// 将JsonObject(字典或数组)中的null元素替换为空字符串,可以用来避免转模型时的一些异常
/// - Parameter jsonObject: Array或者Dictionary,其他类型会返回传入的对象
/// - Returns: 不带null的对象
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
}