我正在努力使用Swift的Decodable正确解码某些数据。我对此的经验有限,但是在获取一组数据中的嵌套字符串数组时遇到了问题。我尝试从中解码的示例API响应为:
{
"data": [
{
"name": "Arnold",
"catchphrases": [
"Ill be back",
"Hasta la vista baby",
"Get to the chopper"
]
},
{
"name": "Doc Brown",
"catchphrases": [
"Great Scott",
"Where we are going we dont need roads"
]
}
]
}
我已经建立了这样的结构:
struct Character: Decodable {
let name: String
let catchphrases: [String]
}
struct CharacterCast: Decodable {
let characters: [Character]
private enum CodingKeys: String, CodingKey {
case data = "data"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
characters = try container.decode([Character].self, forKey: .data)
}
}
由于某种原因,字符串数组给我带来了问题。我不断收到错误消息:The data couldn’t be read because it is missing.
我不确定是什么问题,但我敢打赌它很简单。我知道我不需要较小结构的编码键,因为属性将直接映射(由于完全匹配)。
不确定您的代码,但至少要避免将结构命名为Data
,Character
。另外,请注意查看它是对象还是数组。
let json = """
{
"data": [
{
"name": "Arnold",
"catchphrases": [
"Ill be back",
"Hasta la vista baby",
"Get to the chopper"
]
},
{
"name": "Doc Brown",
"catchphrases": [
"Great Scott",
"Where we are going we dont need roads"
]
}
]
}
"""
struct MyStruct: Codable {
let data: [Datum]
}
struct Datum: Codable {
let name: String
let catchphrases: [String]
}
let data = json.data(using: .utf8)!
do {
let d = try JSONDecoder().decode(MyStruct.self, from: data)
print(d)
} catch {
print(error)
}