Swift 4 Codable解码json [英] Swift 4 Codable decoding json
问题描述
我正在尝试实现新的 Codable
协议,所以我在我的结构中添加了 Codable
,但是坚持解码JSON 。
I'm trying to implement the new Codable
protocol, so I added Codable
to my struct, but am stuck on decoding the JSON.
这是我之前的经历:
结构-
struct Question {
var title: String
var answer: Int
var question: Int
}
客户-
...
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")
}
这是我现在拥有的,除了我无法找出解码器部分:
Here's what I have now, except I can't figure out the decoder part:
结构-
struct Question: Codable {
var title: String
var answer: Int
var question: Int
}
客户-
...
let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
// Can't get past this part
} else {
print("Not working")
}
它显示无法正常工作,因为我无法通过解码器。解码
部分。有任何想法吗?
It prints "Not working" because I can't get past the decoder.decode
part. Any ideas? Will post any extra code as needed, thanks!
编辑:
API JSON示例:
Sample of 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")
}
推荐答案
如果您的JSON具有结构
If your JSON has a structure
{"themes" : [{"title": "Foo", "answer": 1, "question": 2},
{"title": "Bar", "answer": 3, "question": 4}]}
您需要与 themes
对象等效。添加此结构
you need an equivalent for the themes
object. Add this struct
struct Theme : Codable {
var themes : [Question]
}
现在您可以解码JSON了:
Now you can decode the JSON:
if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
print("decoded:", decoded)
} else {
print("Not working")
}
包含的 Question
对象被隐式解码
这篇关于Swift 4 Codable解码json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!