【发布时间】:2018-03-07 17:39:49
【问题描述】:
我正在尝试将 Met Office 中的以下 JSON 转换为 Swift 4 中的对象,但遇到了错误。我的计划是在 JSON 被解码后存储在 Core Data 中。这是返回的一些 JSON
let json = """
{
"Locations":
{
"Location":
[
{
"elevation": "50.0",
"id": "14",
"latitude": "54.9375",
"longitude": "-2.8092",
"name": "Carlisle Airport",
"region": "nw",
"unitaryAuthArea": "Cumbria"
},
{
"elevation": "22.0",
"id": "26",
"latitude": "53.3336",
"longitude": "-2.85",
"name": "Liverpool John Lennon Airport",
"region": "nw",
"unitaryAuthArea": "Merseyside"
}
]
}
}
""".data(using: .utf8)!
我创建了一个结构,用于将数据转换为:
struct locations: Decodable {
var Locations: [location]
struct location: Decodable {
var Location: [MetOfficeLocation]
struct MetOfficeLocation: Decodable {
var elevation: String
var id: String
var latitude: String
var longitude: String
var obsSource: String?
var name: String
var region: String
var area: String
private enum CodingKeys: String, CodingKey {
case elevation
case id
case latitude
case longitude
case obsSource
case name
case region
case area = "unitaryAuthArea"
}
}
}
}
然后我使用 JSONDecoder 进行转换:
let place = try JSONDecoder().decode([Location].self, from: json)
for i in place {
print(i.Location[0].name)
}
我收到一个 keyNotFound 错误,其中没有与关键位置关联的值 (\"locations\")。”我很困惑,因为我不确定位置应该与什么值相关,因为它只是位置
谢谢
【问题讨论】:
-
与手头的问题无关,JSON 的结构没有意义。值得注意的是,与名为
Location的键关联的对象不是单个位置,而是它们的数组,这似乎很奇怪。坦率地说,感觉整个结构层都没有增加价值。我还会亲自更改这些数字字段以返回不带引号的值,因此您可以将它们解析为数字而不是字符串。
标签: json swift jsondecoder