如何使用Swift Decodable协议解码嵌套的JSON结构?

如何使用Swift Decodable协议解码嵌套的JSON结构?,第1张

如何使用Swift Decodable协议解码嵌套的JSON结构?

另一种方法是创建一个与JSON紧密匹配的中间模型(借助于quicktype.io之类的工具),让Swift生成对它进行解码的方法,然后在最终数据模型中挑选所需的片段:

// snake_case to match the JSON and hence no need to write CodingKey enums / structfileprivate struct RawServerResponse: Decodable {    struct User: Decodable {        var user_name: String        var real_info: UserRealInfo    }    struct UserRealInfo: Decodable {        var full_name: String    }    struct Review: Decodable {        var count: Int    }    var id: Int    var user: User    var reviews_count: [Review]}struct ServerResponse: Decodable {    var id: String    var username: String    var fullName: String    var reviewCount: Int    init(from deprer: Deprer) throws {        let rawResponse = try RawServerResponse(from: deprer)        // Now you can pick items that are important to your data model,        // conveniently depred into a Swift structure        id = String(rawResponse.id)        username = rawResponse.user.user_name        fullName = rawResponse.user.real_info.full_name        reviewCount = rawResponse.reviews_count.first!.count    }}

如果

reviews_count
将来它包含多个值,这还使您可以轻松地进行迭代。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5622442.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存