2

🐻Swift中Json转Model的便捷方式

 2 years ago
source link: https://juejin.cn/post/7019910939340193805/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2021年10月17日 阅读 995

🐻Swift中Json转Model的便捷方式

不仅仅是JSON 到 Model

  • string <-> model
  • data <-> model
  • dict <-> model

在Swift的实际开发中,json -> model 并不需要借助第三方pod,官方提供的Coadble大部分可以满足情况,有时我们需要的不仅仅 jsonstr -> model,有时还需要,model -> string(data\dict)。

因此我将其封装到了SpeedySwift加速库中。

使用示例

show my code

    let model = jsonstr.toModel(GroceryProduct.self)
    
    let data = model?.toData()
    
    let dict = model?.toDict()
    
    let dict2 = data?.toDict()
    
    let model2 = data?.toModel(GroceryProduct.self)
复制代码

如何屏蔽Codable解析某个字段?

    struct Parameters: SSCoadble {
        var size: String?
        var area: String?
        var quality: Quality?
        /// 如果json中没有该属性,但是自己想用,可以添加lazy并初始化
        lazy var isSelected:Bool = false
    }
复制代码

例如以上代码中,isSelected并没有在json中体现,而是我的业务标记。

我就可以通过添加lazy并初始化的方式,屏蔽Codable解析该字段

如何映射属性

不同语言的命名方式不同,有大驼峰、小驼峰、下划线,可能服务端和我们客户端命名有区别。

struct GroceryProduct: Codable {
    var ID: Int
    var name: String
    var points: Int?
    var description: String?
    
    enum CodingKeys: String, CodingKey {
        case ID = "id"
        case name
        case points
        case description
    }
}
复制代码

如上述结构中的 id、ID。

我们需要 在enum CodingKeys: String, CodingKey方法中进行映射。

对Codable进行扩展

增加其转换为字典、Data的能力

public protocol SSCoadble: Codable{
    func toDict()->Dictionary<String, Any>?
    func toData()->Data?
}
复制代码

对SSCoadble,增加toDict()toData()的默认实现

public extension SSCoadble{
    
    func toData()->Data?{
        return try? JSONEncoder().encode(self)
    }
    
    func toDict()->Dictionary<String, Any>? {
        if let data = toData(){
            do{
                return try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
            }catch{
                 debugPrint(error.localizedDescription)
                return nil
            }
        }else{
            debugPrint("model to data error")
            return nil
        }
    }
}
复制代码

还有其他json、data、string、dict相互转换的小功能,请在我的开源库SpeedySwift中查看。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK