CleanJSON的用法 swift

 

下载地址  

https://github.com/Pircate/CleanJSON

三种用法

1.Data二进制流转model

2.Array数组转model

3.Dictionary字典转model

 

let decoder = CleanJSONDecoder()
try decoder.decode(Model.self, from: data)

// 支持直接解析符合 JSON 规范的字典和数组
try decoder.decode(Model.self, from: ["key": value])

 

示例 model 遵循 Codable 协议

class HomeVideoModel: Codable {
    var duration: Int = 0
    var likeCount: Int = 0
    var collectCount: Int = 0
    var visitCount: Int = 0

    var videoId: Int = 0
    var userId:Int = 0
    var userName:String?
    var userAvatarUrl:String?
    var userCompany:String?
    var userDept:String?
    var userPosition:String?
    var name: String?
    var expertTag: String?
    var mediaOssUrl: String?
    var previewUrl: String?
    var commentCount: Int = 0
    var isLike: Bool = false
    var isCollect: Bool = false
    var topStatus: HomeTopStatus?
    var tagList: [HomeVideoTagItem]?
    var goodslist: [HomeGoodsItem]?
}

 

 

以下是官方字典转model方式,但是经常解析失败,才有了以上的三方库

https://www.jianshu.com/p/a73c3874c48a?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

 

 

没有选择SwiftyJSON的原因:

Codable 进行了model化,但Codable遇到了同样的问题:

如果我使用了错误的类型,Codable没有做任何处理,并且会导致解析失败,整个model类无法初始化,如果是粗心的程序员,可能会导致crash。

posted @ 2022-06-22 11:59  黄增松  阅读(352)  评论(0编辑  收藏  举报