ios - Swift:任何数组不符合协议“可解码”
问题描述
我正在解码一个 json 响应,但我得到了不同对象的数组。这是我的实现:
public struct MyDecodable: Decodable {
public var id: Int
public var name: String
public var someData: [Any]
}
这是我的错误:
我对你们中的任何人的问题是,我怎样才能使这个实现符合协议Decodable
?
我会非常感谢你的帮助
解决方案
Decodable
协议需要一个带有解码器的初始化程序,就像文档说的那样:
/// A type that can decode itself from an external representation.
public protocol Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
init(from decoder: Decoder) throws
}
默认情况下,对于简单类型或其他 Decodable 实现的类型,可以省略初始化程序,因为 Swift 可以自动将您的 JSON 对象映射到您的 Swift 对象。
在您的情况下,该Any
类型不是 Decodable :
Value of protocol type 'Any' cannot conform to 'Decodable', only struct/enum/class types can conform to protocols
因此,您应该使用特定的泛型类型键入您的数组(这是更好的解决方案),或者在解码初始化程序中编写特定的解码过程:
public struct MyDecodable: Decodable {
public var id: Int
public var name: String
public var someData: [Any]
enum CodingKeys: String, CodingKey {
case id
case name
case someData
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
// Do your stuff here to evaluate someData from your json
}
}
更多信息(Swift4):https ://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375
推荐阅读
- javascript - 我正在尝试打开模式,但前提是用户单击复选框以同意 ToS
- asp.net-mvc - 使用 web api 从一个 localhost 应用程序检索数据到另一个 localhost 应用程序
- asp.net - 从 Asp.Net 网站外部访问 Azure Blob 存储
- python-3.x - 如何对具有其中一列作为版本号的数据框进行排序?
- javascript - 如何在javascript中排序和获取最后一个值和索引
- laravel - 当我使用 laravel 按 created_at 日期搜索订单时,我想显示订单状态
- node.js - 如何在共享主机上托管 Gatsby+Node.js 项目?
- firefox - 动画定义路径的 d 属性在 Firefox 上不起作用
- angular - 无法在 Angular 中延迟加载功能模块
- azure-devops - 从 Spinnaker 触发 Azure DevOps 发布管道阶段