简体   繁体   中英

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

I have a dictionary and I want to convert to jsonstring.

Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols How to fix it? Thanks.

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)
        }
    }
}

You need to give the body type something that conforms to Codable . To fix this issue create another struct that conforms to Codable and change the type of body variable to it.

Here's an example:

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)
        }
    }
}

Or you can use JSONSerialisation like this:

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)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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