Codable [String:Any]字典

问题描述 投票:0回答:2

在我的代码中,我有一个类,其属性类型为[String: Any]。在实施Codable协议时,编译器显示错误,提示

Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols

open class MMSDKNotification: Codable {

    enum MMSDKNotificationKeys: String, CodingKey { // declaring our keys
        case id = "id"
        case message = "message"
        case isRead = "isRead"
        case creationTime = "creationTime"
    }

    public var id: Int = 0
    public var message: [String: Any]?
    public var isRead: Bool = false
    public var creationTime: Int = 0

    required public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: MMSDKNotificationKeys.self) // defining our (keyed) container

        self.id = try container.decode(Int.self, forKey: .id)

        // Here is the error:
        // Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols

        self.message = try container.decode(String.self, forKey: .type)

        self.isRead = try container.decode(Bool.self, forKey: .isRead)
        self.creationTime = try container.decode(Int.self, forKey: .creationTime)

    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: MMSDKNotificationKeys.self)

        try container.encode(id, forKey: .id)
        try container.encode(isRead, forKey: .isRead)
        try container.encode(creationTime, forKey: .creationTime)
    }
}

是否可以将Codable[String: Any]词典一起使用?

swift codable
2个回答
0
投票

是否可以将Codable与[String:Any]词典一起使用?

不,您不能使用Codable,您必须显式编写应符合Codable的类型,否则应使用SwiftyJSON / JSONSerialization


0
投票

是否可以将Codable与[String:Any]词典一起使用?

不,您不能使用Codable,但可以在新模型中创建此词典。

替换

public var message:[String:任何]?

公共变量消息:MessageModel?

struct MessageModel:可编码{}

© www.soinside.com 2019 - 2024. All rights reserved.