简体   繁体   中英

local JSON Enum decoding

How can I decode JSON to Enum in my model? where am i doing wrong? If you wish, I can share my Json decode codes, but my json decode codes are working fine.

Error:

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

Local 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
        },
        ....
    ]
}

Model

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?
}

sections property on Question needs to be a dictionary

struct Question: Codable, Hashable {
    var number: Int?
    var question: String?
    var sections: [Section: String]?
    var price: Int?
    var correct: Int?
}

If you have static 4 keys

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"
    }
}

otherwise use a dictionary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM