如何使用 Swift Decodable 协议解码嵌套的 JSON 结构? [英] How to decode a nested JSON struct with Swift Decodable protocol?

查看:52
本文介绍了如何使用 Swift Decodable 协议解码嵌套的 JSON 结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 JSON

{
    "id": 1,
    "user": {
        "user_name": "Tester",
        "real_info": {
            "full_name":"Jon Doe"
        }
    },
    "reviews_count": [
        {
            "count": 4
        }
    ]
}

这是我想要保存的结构(不完整)

Here is the structure I want it saved to (incomplete)

struct ServerResponse: Decodable {
    var id: String
    var username: String
    var fullName: String
    var reviewCount: Int

    enum CodingKeys: String, CodingKey {
       case id, 
       // How do i get nested values?
    }
}

我已经查看了关于解码嵌套结构的 Apple 文档,但我仍然不明白如何正确处理不同级别的 JSON.任何帮助将不胜感激.

I have looked at Apple's Documentation on decoding nested structs, but I still do not understand how to do the different levels of the JSON properly. Any help will be much appreciated.

推荐答案

另一种方法是创建一个与 JSON 紧密匹配的中间模型(借助像 quicktype.io),让 Swift 生成解码它的方法,然后在最终数据模型中挑选出你想要的部分:

Another approach is to create an intermediate model that closely matches the JSON (with the help of a tool like quicktype.io), let Swift generate the methods to decode it, and then pick off the pieces that you want in your final data model:

// snake_case to match the JSON and hence no need to write CodingKey enums / struct
fileprivate 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 decoder: Decoder) throws {
        let rawResponse = try RawServerResponse(from: decoder)

        // Now you can pick items that are important to your data model,
        // conveniently decoded 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,如果将来它包含 1 个以上的值.

This also allows you to easily iterate through reviews_count, should it contain more than 1 value in the future.

这篇关于如何使用 Swift Decodable 协议解码嵌套的 JSON 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆