swift基于HandyJSON的封装,使用范型
2018-12-07 本文已影响0人
FelixZheng
在之前开发中,直接是基于Codable的解析封装,然在实际项目使用中,经常碰都很多解析问题,最近改成基于HandyJSON的封装
首先定义一个基类
import UIKit
import HandyJSON
/**对象基类*/
class HandyBaseModel : HandyJSON{
required init() {}
func mapping(mapper:HelpingMapper) {
}
}
再实现一个工具类
/// 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
}
/** 对象转JSON */
static func modelToJson(_ model:HandyBaseModel?) -> String{
if model == nil {
print(MapError.modelToJsonFailed)
return ""
}
return(model?.toJSONString())!
}
/** 对象转字典 */
static func modelToDictionary(_ model:HandyBaseModel?) -> [String:Any] {
if model == nil{
print(MapError.modelToJsonFailed)
return [:]
}
return(model?.toJSON())!
}
}
定义一个测试类
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)