如何解析CodingKeys中未定义的JSON

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

考虑以下 JSON:

{
  "jsonName": "fluffy",
  "color1": "Blue",
  "color2": "Red",
  "color3": "Green",
  "color4": "Yellow",
  "color5": "Purple"
}

模型对象:

struct Cat: Decodable {
    let name: String
    let colors: [String]

    private enum CodingKeys: String, CodingKey {
        case name = "jsonName"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
    
        // How to parse all the items with colorX into the colors property???
    }   
}

最多可以有 10 种颜色,但其中一些可能是空字符串。

我尝试了

decode
方法的几种变体,但我不知道如何使用像
color\(i)
这样的标识符。

json swift codable decodable
1个回答
0
投票

一个简单但可能不太优雅的解决方案是将 json 解码为字典

let result = try JSONDecoder().decode([String: String].self, from: data)

然后将 init 添加到以字典作为参数的自定义类型

extension String: Error {} //Replace with custom error type

init(dictionary: [String: String]) throws {
    guard let name = dictionary["jsonName"] else { throw "No key jsonName was found") }
    self.name = name
    colors = dictionary.values.filter { $0.starts(with: "color") }
}
© www.soinside.com 2019 - 2024. All rights reserved.