总是抛出“与键CodingKeys没有关联的值”错误

时间:2019-11-26 18:10:26

标签: ios swift swift5

我有这个可分解的结构:

struct MyDecodableTester: Decodable {
    let id: Int
    let name: String
    let snakeCase: String
    let mappedCodingKey: String

    enum CodingKeys: String, CodingKey {
        case id
        case name
        case snakeCase
        case mappedCodingKey = "code_key"
    }

    static func decode(from data: Data) -> Self? {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        do {
            return try decoder.decode(Self.self, from: data)
        } catch {
            print(">>> Error: \(error)")
        }

        return nil
    }
}

我尝试使用以下JSON调用decode(from data:)函数:

{
"id": 1,
"name": "name",
"snake_case": "snake_case",
"code_key": "code_key"
}

问题是,它总是抛出此错误:

  

keyNotFound(CodingKeys(stringValue:“ code_key”,intValue:nil),   Swift.DecodingError.Context(codingPath:[],debugDescription:“否   与键CodingKeys(stringValue:\“ code_key \”,   intValue:nil)(\“ code_key \”)。“,底层错误:nil))

即使我在下面添加了init(from coder:)函数,由于mappedCodingKey为nil,它始终会崩溃。

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    id = try container.decodeIfPresent(Int.self,
                                           forKey: .id)!
    name = try container.decodeIfPresent(String.self, forKey: .name)!
    snakeCase = try container.decodeIfPresent(String.self,
                                             forKey: .snakeCase)!
    mappedCodingKey = try container.decodeIfPresent(String.self,
                                            forKey: .mappedCodingKey)!
}

我相信我的JSON已经正确,所以我不知道为什么会发生错误。我有什么想念的吗?我该如何解决?

0 个答案:

没有答案