iOS SmartCodable 替换 HandyJSON 适配记录

前言

HandyJSON群里说建议不要再使用HandyJSON,我最终选择了SmartCodable 来替换,原因如下:

首先按照 SmartCodable 官方教程替换

大概要替换的内容如图:

详细的替换教程请前往:使用SmartCodable 平替 HandyJSON

忽略key的解析

在 SmartCodable 中可以使用 @IgnoredKey很方便的忽略解析 某个 Key

使用场景:

在 model 中 加入了一个默认不支持解析的字段,也不需要解析的时候,就需要加@IgnoredKey 来标识忽略解析
示例

swift 复制代码
class GetDailyPlansListModel: SmartCodable{
required init() { }
var should_study_time: String = ""
var dayCompareType = StudyDayCompare.today
}

编译报错
Cannot automatically synthesize 'Encodable' because 'StudyDayCompare' does not conform to 'Encodable'
修改

swift 复制代码
class GetDailyPlansListModel: SmartCodable{
required init() { }
var should_study_time: String = ""
@IgnoredKey
var dayCompareType = StudyDayCompare.today
}

项目中同时使用了WCDB 解决冲突

如果这个 model 同时要用来解析 json 和 存数据库,那么
注意了: 解析只会解析 CodingKeys 里面定义的字段
最简单的适配 :自然是将你要解析的字段在 CodingKeys 中补全
还有一个思路:将数据解析和数据缓存分别用一个 model ,这个项目逻辑复杂的话,会非常麻烦,但如果不想存多余的字段,也只有这样了

swift 复制代码
class GiftGoodsModel: SmartCodable,TableCodable {
    required init() {}
    
    var id:Int = 0 // 礼包商品id
    var ios_goods_id:String = "" // ios商品id "com.yuanlue.cxs.baijuyi",
    var name: String = "" //"庭院诗人-白居易",
    var price:Int = 0 //商品价格
    var source_price:Int = 0 //商品原价
    var pic:String = "" //商品图片
    var recommend:Bool = false //是否推荐
    
    //MARK: ==凑单
    var good_id:Int = 0 //商品id
    //MARK: ==购物车
    var count:Int = 0 //商品数量
    
    var gift_pack_id:Int? //礼包id(字段可空,有值是礼包,无值是普通商品)
    
    enum CodingKeys: String, CodingTableKey {
        typealias Root = GiftGoodsModel
        static let objectRelationalMapping = TableBinding(CodingKeys.self)
        case id
        case ios_goods_id
        case name
        case price
        case source_price
        case pic
        case recommend
        case good_id
        case count
        case gift_pack_id
    }
}

遇到解析 model 就会稍微麻烦点,要在CodingKeys 中将这个model key 加入,WCDB 不支持这种类型,就要去自定义字段映射。

详细教程前往 WCDB 官方文档查看:Swift 自定义字段映射类型

总结

以上便是我使用SmartCodable 替换 HandyJSON中遇到的值得记录的地方。改动 460个地方,替换时间 1.5 天,就是数据库冲突的解决比较耗时,如果没有跟我一样使用 WCDB 的话,替换应该挺轻松地。


感谢您的阅读和参与,HH思无邪愿与您一起在技术的道路上不断探索。如果您喜欢这篇文章,不妨留下您宝贵的赞!如果您对文章有任何疑问或建议,欢迎在评论区留言,我会第一时间处理,您的支持是我前行的动力,愿我们都能成为更好的自己!

相关推荐
pop_xiaoli30 分钟前
OC—UI学习-2
学习·ui·ios
90后的晨仔4 小时前
git 命令汇总
ios
liucan2336 小时前
JS执行速度似乎并不比Swift或者C语言慢
前端·ios
安和昂9 小时前
【iOS】 Block再学习
学习·ios·cocoa
pop_xiaoli9 小时前
OC学习—命名规范
学习·ios
Digitally13 小时前
如何在没有 iTunes 的情况下备份 iPhone
ios·iphone
HarderCoder13 小时前
ByAI:iOS 生命周期:AppDelegate 与 SceneDelegate 中的 `willEnterForeground` 方法解析
swift
大熊猫侯佩14 小时前
SwiftData 如何在 Widgets 和 App 的界面之间同步数据变化?
swiftui·swift·apple watch
YungFan14 小时前
SwiftUI-Preference
swiftui·swift