我使用了别人的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/