首页 > 解决方案 > 如何通过 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)
    ...   
}

标签: swiftreflectionjsondecoder

解决方案


推荐阅读