[英]local JSON Enum decoding
如何在我的模型中將 JSON 解碼為 Enum? 我哪里做錯了? 如果你願意,我可以分享我的 Json 解碼代碼,但我的 json 解碼代碼工作正常。
錯誤:
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "questions", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "sections", intValue: nil)], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
Question_App/JSONProvider.swift:55: Fatal error: Error decoding JSON
本地 JSON
{
questions: [
....
{
"number": 1,
"question": "What is the chemical formula for water ?",
"sections": {
"A": "CO2",
"B": "H2O",
"C": "C2H6O",
"D": "H2N"
},
"price": 5,
"correct": 1
},
....
]
}
模型
struct QuestionContainer: Codable, Hashable {
var questions: [Question]?
}
enum Section: String, Codable, Hashable {
case A, B, C, D
}
struct Question: Codable, Hashable {
var number: Int?
var question: String?
var sections: Section?
var price: Int?
var correct: Int?
}
Question
上的sections
屬性需要是字典
struct Question: Codable, Hashable {
var number: Int?
var question: String?
var sections: [Section: String]?
var price: Int?
var correct: Int?
}
如果您有靜態 4 個鍵
struct Section: Codable, Hashable {
var a, b, c, d:String
private enum CodingKeys: String, CodingKey {
case a = "A"
case b = "B"
case c = "C"
case d = "D"
}
}
否則使用字典
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.