动态字典名称解码器json [英] dynamic dictionary name decoder json
问题描述
Swift4.我与在动态类型/对象,但对我而言,变化的变量是字典的名称,而不是内部的键.看起来像:
Swift 4. I'm in a very similar situation than Using Codable on a dynamic type/object but for me the changing variable is the name of the dictionary and not the keys inside. It looks like :
{
"customName": {
"constantKey": Double,
"constantKey2": Double,
}
}
这是我要更改的代码,有人提出将其作为其他问题的答案,而我所做的更改很少:
Here is the code i'm trying to change, it has been proposed as the answer for the other question and i did little changes :
struct GenericCodingKeys: CodingKey {
var intValue: Int?
var stringValue: String
init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
init?(stringValue: String) { self.stringValue = stringValue }
static func makeKey(name: String) -> GenericCodingKeys {
return GenericCodingKeys(stringValue: name)!
}
}
struct MyModel: Decodable {
var customName: [String: Double]
private enum CodingKeys: String, CodingKey {
case customName
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
customName = [String: String]()
let subContainer = try container.nestedContainer(keyedBy: GenericCodingKeys.self, forKey: .customName)
for key in subContainer.allKeys {
customName[key.stringValue] = try subContainer.decode(Double.self, forKey: key)
}
}
}
这是我遇到的明显错误,因为我不知道如何更改此自定义名称:keyNotFound(Testapp.MyModel.(CodingKeys in _7A951077E4B6EF2E56D367C5DE0BF0AC).customName, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get KeyedDecodingContainer<GenericCodingKeys> -- no value found for key \"customName\"", underlyingError: nil))
And here is the obvious error i got as i don't know how to change this custom name : keyNotFound(Testapp.MyModel.(CodingKeys in _7A951077E4B6EF2E56D367C5DE0BF0AC).customName, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get KeyedDecodingContainer<GenericCodingKeys> -- no value found for key \"customName\"", underlyingError: nil))
推荐答案
如果您已经知道内部JSON中的所有键,请使用结构体来利用静态类型.假设JSON顶层只有1个键(您的customName
键):
If you already know all the keys in the inner JSON, use a struct to take advantage of static typing. Assuming that there's only 1 key on the top level in your JSON (your customName
key):
struct MyModel: Decodable {
struct InnerModel: Decodable {
var constantKey1: Double
var constantKey2: Double
}
var customName: InnerModel
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: GenericCodingKeys.self)
// Assume that there's only 1 key at the top level in the JSON
if let key = container.allKeys.first {
customName = try container.decode(InnerModel.self, forKey: key)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "JSON is empty"])
}
}
}
这篇关于动态字典名称解码器json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!