json - 如何使用 Swift Decodable 协议(protocol)解码嵌套的 JSON

这是我的 JSON

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

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

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's Documentation关于解码嵌套结构,但我仍然不明白如何正确执行不同级别的 JSON。任何帮助将不胜感激。

最佳答案

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

// snake_case to match the JSON and hence no need to write CodingKey enums
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 个值。

关于json - 如何使用 Swift Decodable 协议(protocol)解码嵌套的 JSON 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44549310/

相关文章:

jquery - 如何使用 JQuery 发布 JSON 数据?

jquery - data.map 不是函数

c - 使用 C 解析 JSON

c# - 使用 .NET 4.0 任务模式使用 HTTPClient .ReadAsAsync 将

c# - 忽略 Json.net 中的空字段

javascript - 如何检查 JavaScript 对象是否为 JSON

java - 用于 Java 的 JWT(JSON Web token )库

android - 获取没有数组名称的 JSONArray?

json - 如何使用从字符串转换为 float64 的类型解码 JSON

javascript - 字符串化(转换为 JSON)具有循环引用的 JavaScript 对象