在之前開發(fā)中,直接是基于Codable的解析封裝孵班,然在實(shí)際項(xiàng)目使用中涉兽,經(jīng)常碰都很多解析問題,最近改成基于HandyJSON的封裝
首先定義一個(gè)基類
import UIKit
import HandyJSON
/**對象基類*/
class HandyBaseModel : HandyJSON{
required init() {}
func mapping(mapper:HelpingMapper) {
}
}
再實(shí)現(xiàn)一個(gè)工具類
/// json工具類
class JsonTool:NSObject{
/** String ---> T */
static func toModel(_ jsonStr:String,_ modelType:T.Type) ->T? {
if jsonStr == "" || jsonStr.count == 0{
return nil
}
return T.deserialize(from: jsonStr)
}
/** Any ---> T */
static func toModel(_ data:AnyObject?,_ modelType:T.Type) ->T? {
if let dic = data as? [String:Any] {
return T.deserialize(from: dic)
}
return nil
}
/** Dic ---> T */
static func toModel(_ dic:[String:Any],_ modelType:T.Type) ->T? {
return T.deserialize(from: dic)
}
/** Any ---> [T] */
static func toModelArray(_ data:AnyObject?,_ modelType:T.Type) ->[T]? {
if let dic = data as? [Any] {
return [T].deserialize(from: dic) as? [T]
}
return nil
}
/** String ---> [T] */
public static func toModelArray(_ JSONString:String,_ type:T.Type)throws-> [T]? {
guard let jsonData = JSONString.data(using: .utf8)else{
return nil
}
if let array = try? JSONSerialization.jsonObject(with:jsonData, options: JSONSerialization.ReadingOptions()) as? [AnyObject] {
return JsonTool.toModelArray(arrayasAnyObject, type) ?? nil
}
return nil
}
/** 對象轉(zhuǎn)JSON */
static func modelToJson(_ model:HandyBaseModel?) -> String{
if model == nil {
print(MapError.modelToJsonFailed)
return ""
}
return(model?.toJSONString())!
}
/** 對象轉(zhuǎn)字典 */
static func modelToDictionary(_ model:HandyBaseModel?) -> [String:Any] {
if model == nil{
print(MapError.modelToJsonFailed)
return [:]
}
return(model?.toJSON())!
}
}
定義一個(gè)測試類
class TextModel:HandyBaseModel {
var name:String?
var age:Int?
required init() {}
}
具體使用
let dic = ["name":"小明","age":18] as [String:Any]
let model = JsonTool.toModel(dic,TextModel.self)
print(model?.name)