[英]Swift 4 Codable decoding json
我正在嘗試實現新的Codable
協議,所以我將Codable
添加到我的結構中,但我仍然堅持解碼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")
}
這就是我現在所擁有的,除了我無法弄清楚解碼器部分:
結構 -
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")
}
它打印“不工作”,因為我無法通過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")
}
如果你的JSON有一個結構
{"themes" : [{"title": "Foo", "answer": 1, "question": 2},
{"title": "Bar", "answer": 3, "question": 4}]}
你需要一個等效的themes
對象。 添加此結構
struct Theme : Codable {
var themes : [Question]
}
現在您可以解碼JSON:
if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
print("decoded:", decoded)
} else {
print("Not working")
}
包含的Question
對象被隱式解碼。
您收到此錯誤是因為您的JSON可能是這樣構造的:
{
"themes": [
{ "title": ..., "question": ..., "answer": ... },
{ "title": ..., "question": ..., "answer": ... },
{ ... }
],
...
}
但是,您編寫的代碼需要頂級的[Question]
。 你需要的是一個不同的頂級類型,它具有一個[Question]
的themes
屬性。 當您解碼該頂級類型時,您的[Question]
將被解碼為themes
鍵。
您好@all我已經為Swift 4添加了JSON編碼和解碼的代碼。
請使用此處的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.