繁体   English   中英

swift 将字典转换为 jsonString 错误:协议类型 'Any' 不能符合 'Encodable' 因为只有具体类型才能符合协议

[英]swift Convert dictionary to jsonString error : Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols

我有一本字典,我想转换为 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)
        }
    }
}

你需要给身体类型一些符合Codable的东西。 要解决此问题,请创建另一个符合struct的结构Codable 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)
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM