【问题标题】:local JSON Enum decoding本地 JSON 枚举解码
【发布时间】: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


【解决方案1】:

如果你有静态的 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"
    }
}

否则使用字典

【讨论】:

    【解决方案2】:

    Question 上的sections 属性需要是字典

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-11
      • 2021-07-15
      • 2015-06-24
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      相关资源
      最近更新 更多