如何使用 Codable 协议解码具有嵌套字典的 json



我正在尝试使用可编码的协议解码下面的json:

let jsonData = """
{
"request_state": 200,
"dynamic_value_1": {
"temperature": {
"sol":285.1
}
},
"dynamic_value_2": {
"temperature": {
"sol":405.1
}
}
}
""".data(using: .utf8)!

我使用自定义 init 创建了对象,以便正确映射 json 响应。但我不知道如何映射

public struct Periods: Codable {
public var innerDict: [String: InnerValue]
public struct InnerValue: Codable {
public let temperature: Temperature
}
private struct CustomCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
self.innerDict = [String: InnerValue]()
for key in container.allKeys {
let value = try container.decode(InnerValue.self, forKey: CustomCodingKeys(stringValue: key.stringValue)!)
self.innerDict[key.stringValue] = value
}
}
}

然后当我尝试解码时:

let model = try JSONDecoder().decode(Periods.self, from: jsonData)

我有这个错误:

▿ 0 : CustomCodingKeys(stringValue: "request_state", intValue: nil)
- stringValue : "request_state"
- intValue : nil
- debugDescription : "Expected to decode Dictionary<String, Any> but found a number instead."
- underlyingError : nil

任何帮助创建我的对象都可能非常有用!

您必须考虑request_state情况并解码Int

public struct Periods: Decodable {
var requestState = 0
public var innerDict = [String: InnerValue]()
public struct InnerValue: Decodable {
public let temperature: Temperature
}
public struct Temperature: Decodable {
public let sol: Double
}
private struct CustomCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) { self.stringValue = stringValue }
var intValue: Int?
init?(intValue: Int) { return nil }
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
for key in container.allKeys {
if key.stringValue == "request_state" {
requestState = try container.decode(Int.self, forKey: key)
} else {
let value = try container.decode(InnerValue.self, forKey: key)
innerDict[key.stringValue] = value
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新