Swift 4.我的情况与在动态类型/对象上使用 Codable但对我来说,变化的变量是字典的名称,而不是里面的键。看起来像 :
{
"customName": {
"constantKey": Double,
"constantKey2": Double,
}
}
这是我试图更改的代码,它已被提议作为其他问题的答案,我做了一些更改:
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))
如果您已经知道内部 JSON 中的所有键,请使用结构体来利用静态类型。假设您的 JSON 顶层只有 1 个键(您的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"])
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)