我正在尝试实现 Decodable 来解析 json 请求,但 json 请求在对象内部有一个字典。
这是我的代码:
struct myStruct : Decodable {
let content: [String: Any]
}
enum CodingKeys: String, CodingKey {
case content = "content"
}
但我收到这个错误:
类型“MyClass.myStruct”不符合协议“Decodable”
如何将变量声明为字典而不出现此错误?
我非常感谢你的帮助
嗯...从技术上讲你可以做到这一点,但它需要你使用第三方组件SwiftyJSON https://github.com/SwiftyJSON/SwiftyJSON用于字典表示。
另外,我假设你这样做是因为content
可能有非标准化数据,并且您有意将其视为字典。
在这种情况下,请继续执行以下操作:
import SwiftyJSON
struct MyStruct : Decodable {
//... your other Decodable objects like
var name: String
//the [String:Any] object
var content: JSON
}
Here, JSON
是将代表您的字典的 SwiftyJSON 对象。事实上它也可以代表数组。
工作示例:
let jsonData = """
{
"name": "Swifty",
"content": {
"id": 1,
"color": "blue",
"status": true,
"details": {
"array" : [1,2,3],
"color" : "red"
}
}
}
""".data(using: .utf8)!
do {
let test = try JSONDecoder().decode(MyStruct.self,
from: jsonData)
print(test)
}
catch {
print(error)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)