我正在学习Swift Decodable协议,并且遇到了问题。我能够将一个json对象解码为swift对象,但是无法解码数组。
进展顺利:
想象以下json:
let json = """
{
"all" : {
"_id": "59951d5ef2db18002031693c",
"text": "America’s cats, including housecats that adventure outdoors and feral cats, kill between 1.3 billion and 4.0 billion birds in a year.",
"type": "cat",
"user": {
"_id": "5a9ac18c7478810ea6c06381",
"name": {
"first": "Alex",
"last": "Wohlbruck"
}
},
"upvotes": 4,
"userUpvoted": null
}
}
"""
let jsonData = json.data(using: .utf8)
我可以使用以下代码将其解码为Fact对象:
enum Type: String, Decodable {
case cat = "cat"
}
struct Fact {
let id: String
let text: String
let type: Type
let upvotes: Int
enum CodingKeys: CodingKey {
case all
}
enum FactKeys: CodingKey {
case _id, text, type, upvotes
}
}
extension Fact: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let allContainer = try container.nestedContainer(keyedBy: FactKeys.self, forKey: .all)
id = try allContainer.decode(String.self, forKey: ._id)
text = try allContainer.decode(String.self, forKey: .text)
type = try allContainer.decode(Type.self, forKey: .type)
upvotes = try allContainer.decode(Int.self, forKey: .upvotes)
}
}
let decoder = JSONDecoder()
let fact = try decoder.decode(Fact.self, from: jsonData!)
但是api给了我一系列对象:
let json = """
{
"all": [
{
"_id": "59951d5ef2db18002031693c",
"text": "America’s cats, including housecats that adventure outdoors and feral cats, kill between 1.3 billion and 4.0 billion birds in a year.",
"type": "cat",
"user": {
"_id": "5a9ac18c7478810ea6c06381",
"name": {
"first": "Alex",
"last": "Wohlbruck"
}
},
"upvotes": 4,
"userUpvoted": null
},
{
"_id": "5b01a447c6914f0014cc9a30",
"text": "The special sensory organ called the Jacobson's organ allows a cat to have 14 times the sense of smell of a human. It consists of two fluid-filled sacs that connect to the cat's nasal cavity and is located on the roof of their mouth behind their teeth.",
"type": "cat",
"user": {
"_id": "5a9ac18c7478810ea6c06381",
"name": {
"first": "Alex",
"last": "Wohlbruck"
}
},
"upvotes": 4,
"userUpvoted": null
}
]
}
"""
let jsonData = json.data(using: .utf8)
并且我想将其存储在保存我的Fact对象的allFacts数组中>
class Facts: ObservableObject { @Published var allFacts = [Fact]() } let decoder = JSONDecoder() let allFacts = try decoder.decode([Fact].self, from: jsonData!)
我在Fact结构上使用了相同的扩展名。但这给了我一个错误,我完全迷失了一秒钟。知道我该如何解决吗?我是否还需要为该类创建codingKeys?
Expected to decode Array<Any> but found a dictionary instead."
我正在学习Swift Decodable协议,并且遇到了问题。我能够将一个json对象解码为swift对象,但是无法解码数组。顺利进行:想象...
我建议不要弄乱嵌套容器。这比默认的东西效率低。在您的情况下,您将不得不使用nestedUnkeyedContainer
并迭代仍然昂贵的数组。