Swift下面字典(json)和模型的转换

一、swift下使用OC框架

在OC下面字典和模型的转换有些非常好用的第三方框架,如(YYMode, MJExtension等),当然Swift也可以借鉴这两个框架,只是需要创建模型的时候继承自NSObject,并且加上关键字@objcMembers既可。

@objcMembers class CDBaseModel: NSObject, YYModel {
    //swift 借鉴YYModel
    var name:String = ""
    var age:Int = 0
    var uid:String = ""
    
    static func modelCustomPropertyMapper() -> [String : Any]? {
        return [
            "uid":"id",
        ]
    }
}

swift使用原生Codable 协议

1、在用原生Codable协议的时候,需要当前类继承协议Codable,只是swift的枚举、结构体和类都可以继承该协议。这点事OC无法做到的。

enum Gender:String, Decodable {
    case male
    case female
    case other
}

struct BookModel:Codable {
    
    var name:String = ""
    var price:Float = 0
    
}

class PersonModel: NSObject, Codable {
    
    var name:String = ""
    
}

2、在使用Codable协议的时候,一定要确保模型和原始json数据之间的key值的一致性。
列入有一段json字典如下(这里我用的字典)

private var dictionary:[String:Any] = [:]

        self.dictionary["name"] = "天王"
        self.dictionary["age"] = 9
        self.dictionary["sex"] = true

那么你的模型就需要如下实现(当然这是理想状态)

struct UserModel:Codable {
    var name:   String = ""
    var age:    Int = 0
    var sex:    Bool = false
}

3、如果你的模型里面有一个字段如(name_op)并且原始json数据里面没有该值,此时你的模型如果如下。

struct UserModel:Codable {
    var name:   String = ""
    var age:    Int = 0
    var sex:    Bool = false
    var name_op:    String = ""
}

那么你解析成模型的时候会失败,此时需要把不确定的值定义为可选类型。那么不管原始json数据有没有这个字段,都可以解析成功,如果没有,那么该属性为nil。

struct UserModel:Codable {
    var name:   String = ""
    var age:    Int = 0
    var sex:    Bool = false
    var name_op:    String?
}

4、如果你的模型已经设计好了,但是原始json数据里面有个字段和你的字段事冲突的(如你的属性叫 nick 而原始数据为 nick_name ),那么该值是解析不成功的,如果是可选还好,至少能成功,否则就失败。
解决的办法是实现 enum CodingKeys: String, CodingKey {}这个映射关系

struct UserModel:Codable {
    var name:   String = ""
    var age:    Int = 0
    var sex:    Bool = false
    var name_op:    String?
    var nick: String?
      enum CodingKeys: String, CodingKey {
        case name
        case age
        case sex
        case name_op 
        case nick = "nick_name" 
    }
}

5、如果你的模型里面带有嵌套关系,比如你的模型里面有个其他模型或者模型数组,那么只要保证嵌套的模型里面依然实现了对应的协议,和当前模型一样即可。

struct UserModel:Codable {
    var name:   String = ""
    var age:    Int = 0
    var sex:    Bool = false
    var name_op:    String?
    var nick: String?
    //嵌套关系(保证嵌套模型里面同样实现了Codable协议即可)
    var animo_op:   AnimalModel?
    var books_op:   [BookModel]?

      enum CodingKeys: String, CodingKey {
        case name
        case age
        case sex
        case name_op 
        case nick = "nick_name" 
    }
}

6、如果模型里面和原始数据里面的类型不统一,那么这个解析也会以失败告终。而这种情况需要自定义一个类去适配当前属性。最常见的有(Bool和Int,Int和String)这些在后台若类型语言上是不加区分的。所以不确定到底是什么类型,如果随意定义一个那么会失败。
如下:定义了一个可能是Bool或者Int的类型

struct TIntBool:Codable { 
    var int:Int {
        didSet {
            if int == 0 { self.bool = false
            } else { self.bool = true }
        }
    } 
    var bool:Bool {
        didSet {
            if bool { self.int = 1
            } else { self.int = 0 }
        }
    } 
    //自定义解码(通过覆盖默认方法实现)
    init(from decoder: Decoder) throws {
        let singleValueContainer = try decoder.singleValueContainer()
        if let intValue = try? singleValueContainer.decode(Int.self) {
            self.int = intValue
            self.bool = (intValue != 0)
        } else if let boolValue = try? singleValueContainer.decode(Bool.self) {
            self.bool = boolValue
            if boolValue { self.int = 1
            } else { self.int = 0 }
        } else {
            self.bool = false
            self.int = 0
        }
    } 
}

下面是一个Int 或者String类型的

struct TStrInt: Codable {
    var int:Int {
        didSet {
            let stringValue = String(int)
            if  stringValue != string {
                string = stringValue
            }
        }
    } 
    var string:String {
        didSet {
            if let intValue = Int(string), intValue != int {
                int = intValue
            }
        }
    } 
    //自定义解码(通过覆盖默认方法实现)
    init(from decoder: Decoder) throws {
        let singleValueContainer = try decoder.singleValueContainer() 
        if let stringValue = try? singleValueContainer.decode(String.self)
        {
            string = stringValue
            int = Int(stringValue) ?? 0
            
        } else if let intValue = try? singleValueContainer.decode(Int.self)
        {
            int = intValue
            string = String(intValue);
        } else
        {
            int = 0
            string = ""
        }
    }
}

在设计模型的时候,如下赋值

struct UserModel:Codable {
    var name:   String = ""
    var age:    Int = 0
    var sex:    Bool = false
    var name_op:    String?
    var nick: String?
    //嵌套关系(保证嵌套模型里面同样实现了Codable协议即可)
    var animo_op:   AnimalModel?
    var books_op:   [BookModel]?
  
    //数据类型不一样(如果原始数据为Int,模型里面却是String,这个需要单独定义一种数据类型这种数据类型可能是整型、浮点型、布尔型或者字符串)
    var stringInt:  TStrInt?
    var boolInt:    TIntBool?

      enum CodingKeys: String, CodingKey {
        case name
        case age
        case sex
        case name_op 
        case nick = "nick_name" 
        case  animo_op
        case  animo_op
        case  stringInt
        case boolInt
    }
}

若是完成上面几步,基本可以解决字典模型转换的巨大部分问题。贴上我设计的模型。

struct UserModel:Codable {
    
    //1、必选值(这里的声明需要和原始数据对应的类型和字段完全一样,否则解析失败)
    var name:   String = ""
    var age:    Int = 0
    var sex:    Bool = false
    var weight: Double = 0
    var height: Float = 0
    var animo:  AnimalModel = AnimalModel.init()
    var books:  [BookModel] = []
    
    //2、可选值(这里的类型一定要和原始数据一样,原始数据可以不存在,那么解析为空即可)
    var name_op:    String?
    var age_op:     Int?
    var sex_op:     Bool?
    var weight_op:  Double?
    var height_op:  Float?
    var animo_op:   AnimalModel?
    var books_op:   [BookModel]?
    
    //3、key不一样的情况(如果原始数据和模型的key不一样,那么需要实现一个协议‘CodingKeys’自定义映射关系)
    var nick:       String = ""     //对应原始数据的nick_name
    var nick_op:    String?         //对应原始数据的nick_optional
    
    //4、数据类型不一样(如果原始数据为Int,模型里面却是String,这个需要单独定义一种数据类型这种数据类型可能是整型、浮点型、布尔型或者字符串)
    var birthday:   TStrInt?
    var stringInt:  TStrInt?
    var birthday_op:TStrDou?
    var stringDou:  TStrDou?
    var boolInt:    TIntBool?
    var intBool:    TIntBool?
    
    
    //自定义key的映射关系。
    enum CodingKeys: String, CodingKey {
        case name
        case age
        case sex
        case weight
        case height
        case animo
        case books
        
        case name_op
        case age_op
        case sex_op
        case weight_op
        case height_op
        case animo_op
        case books_op
        
        case nick = "nick_name"
        case nick_op = "nick_optional"
         
        case birthday
        case stringInt
        case birthday_op
        case stringDou
        case boolInt
        case intBool
        
    }
     
}

struct AnimalModel:Codable {
    
    var name:String = ""
    
}

struct BookModel:Codable {
    
    var name:String = ""
    var price:Float = 0
    
}

以及创建的字典

    func setupData() {
        self.dictionary["name"] = "天王"
        self.dictionary["age"] = 9
        self.dictionary["sex"] = true
        self.dictionary["weight"] = 177.7
        self.dictionary["height"] = 77.7
        self.dictionary["animo"] = ["name":"小狗"]
        self.dictionary["books"] = [["name":"语文", "price":22],["name":"数学", "price":33]]
        
        self.dictionary["name_op"] = "tiangwang"
        self.dictionary["age_op"] = 11
        self.dictionary["sex_op"] = false
        self.dictionary["weight_op"] = 22.2
        self.dictionary["height_op"] = 22.2
        self.dictionary["animo_op"] = ["name":"阿毛"]
        self.dictionary["books_op"] = [["name":"社会", "price":11.5],["name":"自然", "price":11.6]]
        
        self.dictionary["nick_name"] = "这是一个昵称"
        self.dictionary["nick_optional"] = "这是可选小名"
        
        self.dictionary["birthday"] = 20000102
        self.dictionary["stringInt"] = "123"
        self.dictionary["birthday_op"] = 123456.5
        self.dictionary["stringDou"] = "321"
        self.dictionary["boolInt"] = true
        self.dictionary["intBool"] = 1
    }

三、模型转化用 JSONDecoder,由于 JSONDecoder 需要的是Data类型,所以先要将json转化为Data。

guard let data = try? JSONSerialization.data(withJSONObject: self.dictionary, options: JSONSerialization.WritingOptions.init()) else {
            print("获取JSON失败")
            return
        }
        guard let model = try? JSONDecoder.init().decode(UserModel.self, from: data)  else {
            print("model转化失败,)")
            return
        }
        print("model = \(model)")

四、为了可以通用,设计一个字典模型转化的工具类

struct CDModel {
    
    //单独的字典(json)转模型
    static public func jsonToModel(type:T.Type, json:Any) -> T? where T:Codable {
        
        guard let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []) else {
            return nil
        }
        guard let model = try? JSONDecoder.init().decode(type, from: jsonData) else {
            return nil
        }
        return model
    }
    
    //json数组转模型数组
    static public func jsonToModel(type:T.Type, array:[[String:Any]]) -> [T]? where T:Codable {
        
        guard let jsonData = try? JSONSerialization.data(withJSONObject: array, options: []) else {
            return nil
        }
        guard let result = try? JSONDecoder.init().decode([T].self, from: jsonData) else {
            return nil
        }
        return result
    }
    
    //单个模型转json字符串
    public static func modelToJson(toString model:T) -> String? where T:Encodable {

        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        guard let data = try? encoder.encode(model)else{
            return nil
        }
        guard let jsonStr = String(data: data, encoding: .utf8)else{
            return nil
        }
        return jsonStr
    }
    
    //单个模型转json字典
    public static func modelToJson(toDictionary model:T) -> [String:Any]? where T:Encodable{

        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        guard let data = try? encoder.encode(model) else {
            return nil
        }
        guard let dict = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)as? [String:Any] else {
            return nil
        }
        return dict
    }

}

使用

        guard let model = CDModel.jsonToModel(type: UserModel.self, json: self.dictionary) else {
            return
        }
        print("model = \(model)")
        
        let array = CDModel.jsonToModel(type: UserModel.self, array: [self.dictionary])
        print("array = \(array ?? [])")
        

你可能感兴趣的:(Swift下面字典(json)和模型的转换)