【问题标题】:Codable [String: Any] dictionary [duplicate]可编码 [String: Any] 字典 [重复]
【发布时间】:2020-02-11 14:44:54
【问题描述】:

在我的代码中,我有一个属性类型为[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] 字典一起使用吗?

【问题讨论】:

  • 想想遵守Codable意味着什么。符合Codable 意味着您的类可以与JSON 相互转换。如何将[String: Any] 转换为 JSON 格式?或者换句话说,如何将Any 转换为 JSON 格式?
  • 不能在 Codable 中声明 Any 类型,只需创建符合 Codable 协议的消息模型即可。

标签: swift codable


【解决方案1】:

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

不,您不能使用 Codable,但您可以在新模型中制作这本字典。

替换

public var 消息:[String: Any]?

public var message: MessageModel?

struct MessageModel: Codable { }

【讨论】:

    【解决方案2】:

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

    不,你不能使用 Codable,你必须明确编写应该符合 Codable 的类型,否则使用 SwiftyJSON/JSONSerialization

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多