【发布时间】:2021-09-11 13:07:24
【问题描述】:
如何在我的模型中将 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?
}
【问题讨论】:
-
使
Section成为结构而不是enum可能是另一种解决方案。
标签: ios json swift file-manager