JSON数据 和 模型数据 的转换可以直接使用 Encodable & Decodable 来解决
前提:模型类 必须遵循协议 Codable(包含 Encodable & Decodable)
主要方法:JSONDecoder().decode(<#T##type: Decodable.Protocol##Decodable.Protocol#>, from: <#T##Data#>) 和 JSONEncoder().encode(<#T##value: Encodable##Encodable#>)
代码:
class DataHelper {
class func arrToDict<T: Encodable>(_ arr: [T], _ key: String? = "1") -> [String: Any]? {
let encode = JSONEncoder()
encode.outputFormatting = .prettyPrinted
var dict: [String: Any] = [:]
var arrM: [[String: Any]?] = []
for model in arr {
autoreleasepool {
if let data = try? encode.encode(model) {
if let dic = ((try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String: Any]) as [String : Any]??) {
arrM.append(dic)
}
}
}
}
dict.updateValue(arrM, forKey: key!)
print("- arrToDict -", dict)
return dict
}
class func modelToDict<T: Encodable>(_ model: T) -> [String: Any]? {
let encode = JSONEncoder()
encode.outputFormatting = .prettyPrinted
guard let data = try? encode.encode(model) else {return nil}
guard let dic = ((try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String: Any]) as [String : Any]??) else {return nil}
return dic
}
class func modelToStr<T: Encodable>(_ model: T) -> String? {
let encode = JSONEncoder()
encode.outputFormatting = .prettyPrinted
guard let data = try? encode.encode(model) else {return nil}
guard let dic = ((try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? String) as String??) else {return nil}
return dic
}
class func dictToArr<T: Decodable>(_ dic: [String: Any], _ key: String? = "1") -> [T]? {
guard let arr = dic[key!] as? [Any] else {return nil}
var result: [T] = []
for dict in arr {
autoreleasepool {
if let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
if let value = try? JSONDecoder().decode(T.self, from: data) {
result.append(value)
}
}
}
}
print("- dictToArr -", arr, result)
return result
}
class func dictToModel<T: Decodable>(_ dic: [String: Any]) -> T? {
guard let data = try? JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted) else {return nil}
guard let result = try? JSONDecoder().decode(T.self, from: data) else {return nil}
return result
}
class func strToModel<T: Decodable>(_ str: String) -> T? {
guard let data = try? JSONSerialization.data(withJSONObject: str, options: .prettyPrinted) else {return nil}
guard let result = try? JSONDecoder().decode(T.self, from: data) else {return nil}
return result
}
class func dataToModel<T: Decodable>(_ data: Data) -> T? {
guard let result = try? JSONDecoder().decode(T.self, from: data) else {return nil}
return result
}
}
网友评论