简体   繁体   English

在 swift 中对动态键和动态 object 使用 Codable

[英]Using Codable on a dynamic key and dynamic object in swift

I have the following structure nested in a structure that is returned from an service call but I can't manage to encode/decode this part.我有以下结构嵌套在从服务调用返回的结构中,但我无法对这部分进行编码/解码。 The problem I am having is that the customKey and customValue are both dynamic.我遇到的问题是 customKey 和 customValue 都是动态的。 customValue may be array or dictionary or array of dictionary For Example customValue 可以是数组或字典或字典数组例如

{
    "status": "a string value",
    "id": "a string value",
    "property": {
        "customkey1": "customValue1",
        "customKey2": [{
            "InnerCustomKey": "InnerCustomValue"
        }, {
            "InnerCustomKey": "InnerCustomValue"
        }, {
            "InnerCustomKey": "InnerCustomValue"
        }],
        "customkey3": {
            "InnerCustomKey": "InnerCustomValue"
        }
    }
}

I tried something like var values: [String:String] But it failed in another object.我尝试了类似 var values: [String:String] 但在另一个 object 中失败了。 I follow the answer Using Codable on a dynamic type/object but not getting success我遵循在动态类型/对象上使用 Codable的答案,但没有成功

extension KeyedDecodingContainerProtocol{

    func getValueFromAvailableKey(codingKeys:[CodingKey])-> Any?{
        for key in codingKeys{
            for keyPath in self.allKeys{
                if key.stringValue == keyPath.stringValue{
                    do{
                        if let value = try? self.decodeIfPresent([String].self, forKey:keyPath){
                            return value
                        }

                        if let value = try? self.decodeIfPresent([String:String].self, forKey:keyPath){
                            return value
                        }

                        if let value = try? self.decodeIfPresent([[String:String]].self, forKey:keyPath){
                            return value
                        }

                        if let value = try? self.decodeIfPresent(String.self, forKey:keyPath){
                            return value
                        }

                        return nil
                    }
                }
            }
        }
        return nil
    }
}

private struct CustomCodingKeys: CodingKey {
    var stringValue: String
    init?(stringValue: String) {
        self.stringValue = stringValue
    }
    var intValue: Int?
    init?(intValue: Int) {
        return nil
    }
}

struct CustomModel: Codable {
    var status:String?
    var id: String?
    var property: Property?


    init(from decoder: Decoder)  {
        do{
            let container = try decoder.container(keyedBy: CustomCodingKeys.self)
            status = try container.decodeIfPresent(String.self, forKey: CustomCodingKeys.init(stringValue: "status")!)
            id = try container.decodeIfPresent(String.self, forKey: CustomCodingKeys.init(stringValue: "id")!)
            property = try container.decodeIfPresent(Property.self, forKey: CustomCodingKeys.init(stringValue: "property")!)


        }catch{
            print(error.localizedDescription)
        }
    }

    func encode(to encoder: Encoder) throws {
             var container = encoder.container(keyedBy: CustomCodingKeys.self)
             try? container.encodeIfPresent(self.status, forKey: CustomCodingKeys.init(stringValue: "status")!)
             try? container.encodeIfPresent(self.id, forKey: CustomCodingKeys.init(stringValue: "id")!)
             try? container.encodeIfPresent(self.property, forKey: CustomCodingKeys.init(stringValue: "property")!)
    }
}

// MARK: - Property
struct Property: Codable {
    var customkey:[String:Any?] = [:]

    init(from decoder: Decoder)  {
        do{
            let container = try decoder.container(keyedBy: CustomCodingKeys.self)
            for key in container.allKeys{
                customkey[key.stringValue] = container.getValueFromAvailableKey(codingKeys: [CustomCodingKeys.init(stringValue: key.stringValue)!])
            }

        }catch{
            print(error.localizedDescription)
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CustomCodingKeys.self)
        for key in customkey{
                 try? container.encodeIfPresent(customkey[key.key] as? String, forKey: CustomCodingKeys.init(stringValue: key.key)!)
                 try? container.encodeIfPresent(customkey[key.key] as? [[String:String]], forKey: CustomCodingKeys.init(stringValue: key.key)!)
                 try? container.encodeIfPresent(customkey[key.key] as? [String:String], forKey: CustomCodingKeys.init(stringValue: key.key)!)
            }

    }
}

Hope this will help you !希望对你有帮助 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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