swift - 如何通过 Swift 4.2 中的反射类类型使用 JSONDecoder 解码 JSON?
问题描述
找不到正确的方法来调用decode
具有反射类类型的方法。上面有ambiguous reference
错误。
class EntityTwo: Decodable {
var name: String = ""
}
class EntityOne: Decodable {
var value: String = ""
}
struct Entity: Decodable {
var entity: String
var payload: Any
enum CodingKeys: String, CodingKey {
case entity
case payload
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
entity = try container.decode(String.self, forKey: .entity)
let entityType = NSClassFromString("MyFramework." + entity) as! Decodable.Type
payload = try container.decode(entityType, forKey: .payload)
}
}
遇到问题:
payload = try container.decode(entityType, forKey: .payload) -> Ambiguous reference to member 'decode(_:forKey:)'
在后台它曾经从套接字接收不同的实体:
{
"entity": "EntityOne",
"payload": {
"value": "EntityOneValue"
}
}
{
"entity": "EntityTwo",
"payload": {
"name": "EntityTwoName"
}
}
public func websocketMessage(data: Data) {
let entity = JSONDecoder().decode(Entity.self, from: data)
...
}
解决方案
推荐阅读
- typescript - 我应该如何在 Typescript 中解释这种代码类型检查
- android - 当服务器从 http 切换到 https 时,Android 显示错误
- python - 如何将同义词存储为数据框中的列?
- ruby-on-rails - rspec - Big Sur 中的等 LoadError
- c - printf 自定义实现中的错误
- python - 我可以创建带有小时和秒的动态 x 轴吗?
- python - 我们如何在 Python 中使用 ntplib 库运行本地 ntp 服务器
- python - 如何告诉python从两个重复的行中取出较大的数字
- java - Android HttpURLConnection POST 不工作。使用 C#
- vue.js - 解析未定义的道具?