首页 > 解决方案 > 在 API 调用中使用 Codable 和 Decodable

问题描述

我正在尝试调用APIusingCodable并且我想dictionaryAPI.

这是可能的codable吗?

API 响应例如:

{
    "status": true,
    "logo": "https://abc.png",
    "data": [
        {
            "crumb": {
                "Menu": {
                    "navigate": "Home",
                },
            },
            "path": "2",
            "type": "type0",
            "orientation": [
                {
                    "name": "All",
                }
            ],
        },
    ]
}

标签: iosswiftxcode

解决方案


您发布的 API 响应是无效的 JSON(它有一堆使其非法的尾随逗号)。这需要在生产者方面进行更改,当你这样做时,你可以使用这个结构来访问数据:

struct Entry: Codable {
    let status: Bool
    let logo: String
    let data: [Datum]
}

struct Datum: Codable {
    let crumb: Crumb
    let path, type: String
    let orientation: [Orientation]
}

struct Crumb: Codable {
    let menu: Menu

    enum CodingKeys: String, CodingKey {
        case menu = "Menu"
    }
}

struct Menu: Codable {
    let navigate: String
}

struct Orientation: Codable {
    let name: String
}

推荐阅读