Swift 5中的解码枚举-不能这么难

问题描述 投票:0回答:2

过去的3-4个小时我一直在尝试让这个愚蠢的事情正确地解码此枚举,现在对此感到非常沮丧!我有一个从[API]返回的json字符串,如下所示:

[
  {
    "contractType": 0
  }
]

我正在尝试将THAT映射到名为ContractType的枚举。这是我的整个ContractType枚举

enum ContractType: Int {
    case scavenger = 0
}

这是我的扩展,我试图使其符合Codable协议。

extension ContractType: Codable {
    enum Key: Int, CodingKey {
        case rawValue
    }

    enum CodingError: Error {
        case unknownValue
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Key.self)
        let rawValue = try? container.decode(Int.self, forKey: .rawValue)

        switch rawValue {
        case 0:
            self = .scavenger
        default:
            throw CodingError.unknownValue
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: Key.self)
        switch self {
        case .scavenger:
            try container.encode(0, forKey: .rawValue)
        }
    }
}

我到底在做什么错!?任何帮助将不胜感激!

swift swift5 codable decodable encodable
2个回答
0
投票

您需要,

型号:

struct Response: Codable {
    let contractType: ContractType
}

enum ContractType: Int, Codable {
    case scavenger = 0
}

像这样解析数据,

do {
    let response = try JSONDecoder().decode([Response].self, from: data)
    print(response)
} catch {
    print(error)
}

0
投票

您的枚举必须在json中包含密钥

enum Key: Int, CodingKey {
    case contractType
}
© www.soinside.com 2019 - 2024. All rights reserved.