[英]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.我有一本字典,我想转换为 jsonstring。
Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols How to fix it?
协议类型 'Any' 不能符合 'Encodable' 因为只有具体类型才能符合协议 如何解决? 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
.你需要给身体类型一些符合
Codable
的东西。 To fix this issue create another struct
that conforms to Codable
and change the type of body
variable to it.要解决此问题,请创建另一个符合
struct
的结构Codable
body
变量的类型更改为它。
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:或者您可以像这样使用 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.