美文网首页
Swift 使用JSONDecoder 将data转为model

Swift 使用JSONDecoder 将data转为model

作者: 分享学习 | 来源:发表于2022-08-09 16:47 被阅读0次

    如下 json 数据

    {
        "movie_detail":
            {
                "movie_thumbnail_image":"https://bkimg.cdn.bcebos.com/pic/aa18972bd40735fae6cd4657120318b30f2443a7a299?x-bce-process=image/resize,m_lfit,w_440,limit_1/format,f_auto",
                "title":"长津湖",
                "synopsis":"《长津湖》是由陈凯歌、徐克、林超贤联合执导,吴京、易烊千玺领衔主演,段奕宏、欧豪特别出演,朱亚文、李晨、胡军、韩东君等主演的抗美援朝电影 ,该片于2021年9月30日在中国大陆上映。该片以抗美援朝战争第二次战役中的长津湖战役为背景,讲述了一段波澜壮阔的历史,在极寒严酷环境下,中国人民志愿军东线作战部队凭着钢铁意志和英勇无畏的战斗精神,扭转战场态势,为长津湖战役胜利作出重要贡献的故事。",
                "theater":["A影院","B影院","C影院"],
                "comments":
                    [
                        {"user_name":"user001","rating":"5","comment":"评论1!"},
                        {"user_name":"user002","rating":"5","comment":"评论2!"},
                        {"user_name":"user003","rating":"4","comment":"评论3!"}
                    ]
            }
    }
    

    可以将此 json 数据分为三个模型 MovieDetailDic,MovieDetail,Comment

    首先建立一个 struct 类型的 model -> MovieDetailDic 遵循 Decodable 协议,通过 CodingKey 将模型变量和 json 的 key 对应

    struct MovieDetailDic: Decodable {
        private enum CodingKeys: String, CodingKey {
            case movieDetail = "movie_detail"
        }
        
        let movieDetail: MovieDetail?
        
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            movieDetail = try values.decodeIfPresent(MovieDetail.self, forKey: .movieDetail)
        }
    }
    

    将 json 数据 “movie_detail” 对应的 value 建立为 MovieDetail 模型。 变量要和 json 的 key 相对应, 变量名可以自定义, 但是要在 CodingKeys 中将变量名和 key 关联起来, 如【case movieThumbnailImage = "movie_thumbnail_image"】, 如果变量名 和 key 相同,可不做处理。

    struct MovieDetail: Decodable {
        private enum CodingKeys: String, CodingKey {
            case movieThumbnailImage = "movie_thumbnail_image"
            case title
            case synopsis
            case theater
            case comments
        }
        
        let movieThumbnailImage: String?
        let title: String?
        let synopsis: String?
        let theater: [String]?
        let comments: [Comment]?
    
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            title = try values.decodeIfPresent(String.self, forKey: .title)
            movieThumbnailImage = try values.decodeIfPresent(String.self, forKey: .movieThumbnailImage)
            synopsis = try values.decodeIfPresent(String.self, forKey: .synopsis)
            theater = try values.decodeIfPresent([String].self, forKey: .theater)
            comments = try values.decodeIfPresent([Comment].self, forKey: .comments)
        }
    }
    

    建立 comment 模型

    struct Comment: Decodable {
        private enum CodingKeys: String, CodingKey {
            case userName = "user_name"
            case rating
            case comment
        }
        
        let userName: String?
        let rating: String?
        let comment: String?
        
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            userName = try values.decodeIfPresent(String.self, forKey: .userName)
            rating = try values.decodeIfPresent(String.self, forKey: .rating)
            comment = try values.decodeIfPresent(String.self, forKey: .comment)
        }
    }
    
    

    然后使用 JSONDecoder 解析获得的 data 即可将 json data 转为自定义模型

    let dataList = try! JSONDecoder().decode(MovieDetailDic.self, from: data)
    

    相关文章

      网友评论

          本文标题:Swift 使用JSONDecoder 将data转为model

          本文链接:https://www.haomeiwen.com/subject/ffpnwrtx.html