对成员'decodeIfPresent(_:forKey :)的引用不明确

时间:2019-04-10 20:42:23

标签: swift codable

是否有从[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:"
            },

1 个答案:

答案 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"
    }
}