是否有从[String:Any]编码的代码? 我正在使用SwiftyJSON,看起来编码部分没有给出任何错误
struct MyClass: Codable {
var my_label: [String: Any]?
enum CodingKeys: String, CodingKey {
case my_label = "my_label"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
my_label = try values.decodeIfPresent([String: Any].self, forKey: .my_label)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(JSON(my_label as Any), forKey: .my_label)
}
}
某些示例显示my_label看起来像这样,尽管不能保证这就是为什么
"my_label": {
"condition": {
"IsOpen": "Yes"
},
"label": "Test Completed:"
},
答案 0 :(得分:0)
您可以使用JSONSerialization
,但不能使用Decodable
Any
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
if let res = json["my_label"] as? [String:Any] {
print(res)
}
} catch {
print(error)
}
或
struct Root: Codable {
let myLabel: MyLabel
enum CodingKeys: String, CodingKey {
case myLabel = "my_label"
}
}
struct MyLabel: Codable {
let condition: Condition
let label: String
}
struct Condition: Codable {
let isOpen: String
enum CodingKeys: String, CodingKey {
case isOpen = "IsOpen"
}
}