【发布时间】:2021-10-18 17:51:42
【问题描述】:
Swift 中 Json 的问题 - 尝试解码数据,但出现错误“未找到密钥”。 我用另一个键检查过 - 它可以工作,所以可能是名称错误?
如有任何提示,我将不胜感激!
json:
{
"created": "2021-10-18T14:55:42.537Z",
"count": 2,
"offset": 0,
"places": [
{
"id": "d1ab65f8-d082-492a-bd70-ce375548dabf",
"type": "Studio",
"type-id": "05fa6a09-ff92-3d34-bdbb-5141d3c24f38",
"score": 100,
"name": "Chipping Norton Recording Studios",
"address": "28–30 New Street, Chipping Norton",
"coordinates": {
"latitude": "51.9414",
"longitude": "-1.548"
},
"area": {6 items},
"life-span": {
"begin": "1971",
"end": "1999-10",
"ended": true
}
},
{8 items}
]
}
还有我的数据结构:
import Foundation
struct BrainzData: Codable {
let places: [Places]
}
struct Places: Codable {
var coordinates: Coordinates
var lifespan: LifeSpan
enum CodingKeys: String, CodingKey {
case coordinates
case lifespan = "life-span"
}
}
struct Coordinates: Codable {
let longitude: String
let latitude: String
}
struct LifeSpan: Codable {
let begin: String
var ended: Bool
}
【问题讨论】:
-
完整的错误信息是什么?会不会是 JSON 中缺少值的地方之一,而在您提供的示例中它是正确的?
-
...您使用特定的密钥解码策略吗?
-
我不确定我是否得到你,但正确的样本是“id”。所以我得到了价值。结构也是以同样的方式构建的。完整的错误消息:keyNotFound(CodingKeys(stringValue: "begin", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "places", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "life-span", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"begin\", intValue: nil) (\"begin\") .",基础错误:无))
-
错误涉及数组
places中的第二个 项(索引1),这是不可见{8 items}中的第一个 -
读取 JSON。如果缺少键(在数组项中),则将相应的结构成员声明为可选。