JSON數(shù)據(jù) 和 模型數(shù)據(jù) 的轉(zhuǎn)換可以直接使用 Encodable & Decodable 來(lái)解決
前提:模型類(lèi) 必須遵循協(xié)議 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
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。