一尘不染

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

swift

这是我的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的有关解码嵌套结构的文档,但是我仍然不明白如何正确执行JSON的不同级别。任何帮助都感激不尽。


阅读 205

收藏
2020-07-07

共1个答案

一尘不染

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

// 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将来它包含多个值,这还使您可以轻松地进行迭代。

2020-07-07