使用Swift中的Codable将JSON解析为对象数组而不是字典

ntjbwcob  于 2023-01-29  发布在  Swift
关注(0)|答案(1)|浏览(132)

我从API接收到以下JSON

{
   "someProperty":"someValue",
   "type":"type1",
   "values":{
      "first":"someValue",
      "second":"someValue" // keys and values are always different !
   }
}

我创建了一个模型来解析这个JSON,它工作正常。

struct MyModel: Codable {
    let someProperty: String
    let type: SomeType
    var values: [String: String]?
}

enum SomeType: Codable {
    case type1, type2
}

但是我需要得到对象数组而不是字典。因为我需要以正确的顺序得到值。
我想要这样的东西:

struct MyModel: Codable {
    let someProperty: String
    let type: SomeType
    var values: [Value]?
}

enum SomeType: Codable {
    case type1, type2
}

struct Value: Codable {
    let key: String
    let value: String
}

我不知道我应该在代码中做些什么修改才能让这个模型工作,因为现在我得到了错误"期望解码数组,但却找到了一个字典"。
有没有一种方法可以像我想要的那样解析JSON?有什么建议吗?也许有类似解析的代码示例
感谢您的时间和您的帮助!

anauzrmj

anauzrmj1#

创建一个自定义init,在其中解码字典并将其Map到Value的数组中:

struct MyModel: Codable {
    let someProperty: String
    let type: SomeType
    var values: [Value]?

    enum CodingKeys: CodingKey{
        case someProperty, type, values
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        someProperty = try container.decode(String.self, forKey: .someProperty)
        type = try container.decode(SomeType.self, forKey: .type)
        
        let dictionary = try container.decodeIfPresent([String:String].self, forKey: .values)
        values = dictionary?.map{Value(key: $0.key, value: $0.value)}
    }
}

相关问题