json - 我可以在 Swift 中声明一个名为 'Type' 的变量吗?

标签 json swift struct decode decodable

我使用了别人的API。它返回给我 JSON。像这样;

[{"ID": 123,
 "Name": "My Game Api",
 "Type": "Racing",
 "Num": 0,
 "Country": "England"
}]

我定义了一个结构体来解析 JSON,如下所示:

struct MyResult : Decodable{
    var ID : Int?
    var Name : String?
    var Type : String?
    var Num : Int?
    var Country : String?
}
// Using..
    let games = try JSONDecoder().decode([MyResult].self, from: data!)

当然,xCode 给了我一个错误: 类型成员不能命名为“Type”,因为它会与“foo.Type”表达式冲突。

API 不是我写的。 如果我更改变量类型的名称,我将无法读取该值。

我可以在不修改 API 的情况下使用 Decodable Struct 吗?

最佳答案

您可以像下面这样使用:

struct MyResult : Decodable {
    var ID : Int?
    var Name : String?
    var type : String?
    var Num : Int?
    var Country : String?

    private enum CodingKeys : String, CodingKey {
        case ID, Name, type = "Type", Num, Country
    }
}

尝试关注 Hamish 发布的评论

关于json - 我可以在 Swift 中声明一个名为 'Type' 的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475825/

相关文章:

c - 在 C 中访问传递的结构数组的成员

php - PHP Web 服务的 json 数组响应

arrays - 用节点替换 jq 中从根开始的路径

json - Testcafe - 如何使用 JSON 响应数据作为变量

ios - swift中的音频播放器没有获得音量和音高的值(value)

arrays - Swift:将文本字段保存在数组中

php - 以 JSON 格式输出 SQL 结果数组的正确方法

swift - 使用 Swift 同步访问 Firebase Cloud Firestore

coldfusion - 对嵌套对象使用 structKeyExists

string - 使用反射 SetString