我从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?有什么建议吗?也许有类似解析的代码示例
感谢您的时间和您的帮助!
1条答案
按热度按时间anauzrmj1#
创建一个自定义init,在其中解码字典并将其Map到
Value
的数组中: