【问题标题】:swift Convert dictionary to jsonString error : Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocolsswift将字典转换为jsonString错误:协议类型'Any'不能符合'Encodable',因为只有具体类型才能符合协议
【发布时间】:2020-09-20 13:28:59
【问题描述】:

我有一本字典,我想转换成 jsonstring。

协议类型“Any”不能符合“Encodable”,因为只有具体类型才能符合协议 如何解决?谢谢。

func save(body: [String: Any]) -> Void {

    let encoder = JSONEncoder()
    if let jsonData = try? encoder.encode(body) { //error here.
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}

【问题讨论】:

  • 改用JSONSerialization。但是 Dictionary 和 JSONEncoder 呢?你不使用 Codable 吗?
  • 请仔细阅读错误信息。很清楚,意思就是它所说的。

标签: ios json swift encode


【解决方案1】:

您需要为主体类型指定符合Codable 的内容。要解决此问题,请创建另一个符合 Codablestruct 并将 body 变量的类型更改为它。

这是一个例子:

struct Body: Codable { 
// all the properties you require can be added here.
}

func save(body: Body) -> Void {

    let encoder = JSONEncoder()
    if let jsonData = try? encoder.encode(body) {
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}

或者你可以像这样使用 JSONSerialisation:

func save(body: [String: Any]) -> Void {

    if let jsonData = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) {
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多