我尝试实现新的Codable
协议,所以我将Codable
添加到我的结构体中,但是我在解码JSON时卡住了。
以下是之前的代码:
结构体 -
struct Question {
var title: String
var answer: Int
var question: Int
}
Client -
...
guard let data = data else {
return
}
do {
self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
let questionItems = self.jsonResponse?["themes"] as! [[String: Any]]
questionItems.forEach {
let item = Question(title: $0["title"] as! String,
answer: $0["answer"] as! Int,
question: $0["question"] as! Int)
questionData.append(item)
}
} catch {
print("error")
}
这是我现在拥有的内容,但我无法弄清解码器部分:
结构体 -
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
Client -
...
let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
// Can't get past this part
} else {
print("Not working")
}
因为我无法通过decoder.decode
部分,所以它会打印“不起作用”。有什么想法吗?如有需要,将发布任何额外的代码,谢谢!
编辑:
API JSON示例:
{
"themes": [
{
"answer": 1,
"question": 44438222,
"title": "How many letters are in the alphabet?"
},
{
"answer": 0,
"question": 44438489,
"title": "This is a random question"
}
]
}
如果我打印
self.jsonResponse
,我会得到以下结果:Optional(["themes": <__NSArrayI 0x6180002478f0>(
{
"answer" = 7;
"question" = 7674790;
title = "This is the title of the question";
},
{
"answer_" = 2;
"question" = 23915741;
title = "This is the title of the question";
}
我的新代码:
struct Theme: Codable {
var themes : [Question]
}
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
...
if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
print("decoded:", decoded)
} else {
print("Not working")
}
jsonResponse
的数据,因为那是一个JSON对象,而不是一个数组。你需要从"themes"
键中获取数组(定义另一个具有此属性的Codable
类型)。 - Hamish