尝试对Reddit列表JSON响应上的“已编辑”字段进行解码/编码时遇到了相同的问题。我创建了一个结构,该结构表示给定键可能存在的动态类型。键可以是布尔值或整数。
{ "edited": false }{ "edited": 123456 }如果只需要能够解码,则只需实现init(from :)。如果您需要同时使用两种方法,则需要实现enpre(to :)函数。
struct Edited: Codable { let isEdited: Bool let editedTime: Int // Where we determine what type the value is init(from deprer: Deprer) throws { let container = try deprer.singlevalueContainer() // Check for a boolean do { isEdited = try container.depre(Bool.self) editedTime = 0 } catch { // Check for an integer editedTime = try container.depre(Int.self) isEdited = true } } // We need to go back to a dynamic type, so based on the data we have stored, enpre to the proper type func enpre(to enprer: Enprer) throws { var container = enprer.singlevalueContainer() try isEdited ? container.enpre(editedTime) : container.enpre(false) }}在我的Codable类中,然后使用我的结构。
struct Listing: Codable { let edited: Edited}编辑:针对您的方案的更具体的解决方案
我建议在解码时使用CodingKey协议和一个枚举来存储所有属性。当您创建符合Codable的内容时,编译器将为您创建一个私有枚举CodingKeys。这使您可以根据JSON
Object属性键决定要做什么。
仅举例来说,这就是我正在解码的JSON:
{"type": "1.234"}{"type": 1.234}如果您只想将double值从字符串转换为Double,则只需解码字符串,然后从中创建一个double。(这是Itai
Ferber所做的,然后您还必须使用tryprer.depre(type:forKey :)对所有属性进行解码)
struct JSONObjectCasted: Codable { let type: Double? init(from deprer: Deprer) throws { // Depre all fields and store them let container = try deprer.container(keyedBy: CodingKeys.self) // The compiler creates coding keys for each property, so as long as the keys are the same as the property names, we don't need to define our own enum. // First check for a Double do { type = try container.depre(Double.self, forKey: .type) } catch { // The check for a String and then cast it, this will throw if decoding fails if let typevalue = Double(try container.depre(String.self, forKey: .type)) { type = typevalue } else { // You may want to throw here if you don't want to default the value(in the case that it you can't have an optional). type = nil } } // Perform other decoding for other properties. }}如果需要将类型和值一起存储,则可以使用符合Codable的枚举而不是struct。然后,您可以仅使用具有JSONObjectCustomEnum的“
type”属性的switch语句,并根据大小写执行操作。
struct JSONObjectCustomEnum: Codable { let type: DynamicJSONProperty}// Where I can represent all the types that the JSON property can be. enum DynamicJSONProperty: Codable { case double(Double) case string(String) init(from deprer: Deprer) throws { let container = try deprer.singlevalueContainer() // Depre the double do { let doubleval = try container.depre(Double.self) self = .double(doubleval) } catch DecodingError.typeMismatch { // Depre the string let stringVal = try container.depre(String.self) self = .string(stringVal) } } func enpre(to enprer: Enprer) throws { var container = enprer.singlevalueContainer() switch self { case .double(let value): try container.enpre(value) case .string(let value): try container.enpre(value) } }}


