解码来自JSON的动态键和值

时间:2017-11-16 11:29:22

标签: json swift4 codable

我正在尝试解码JSON,其中包含动态键和值类型。我已经尝试按照问题回答here并且可以获取我的动态密钥,但似乎无法获取值以及它们的类型总是不同的。理想情况下,我希望能够将'parameters'属性作为字典,但我不确定如何解决这个问题。我的代码如下。

let jsonString = """
{
    "type": "some type",
    "message": "some message",
    "parameters": {
        "randomKey": "some value",
        "anotherKey": 99,
        "padlock": "another string",
        "fakeKey": true
        }
    }

"""

struct MyStruct : Decodable {

let type:String!
let message:String!
var parameters:DynamicParameters!

struct DynamicParameters: Decodable {

    var keys:[String]!

    private struct CodingKeys: CodingKey {
        var intValue: Int?
        var stringValue: String

        init?(intValue: Int) { self.intValue = intValue; self.stringValue = "" }
        init?(stringValue: String) { self.stringValue = stringValue }
    }

    init(from decoder: Decoder) throws {
        self.keys = [String]()
        let container = try decoder.container(keyedBy: CodingKeys.self)

        for key in container.allKeys {
            self.keys.append(key.stringValue)
            }
        }
    }
}

if let jsonData = jsonString.data(using: .utf8) {
do {
    let list = try JSONDecoder().decode(MyStruct.self, from: jsonData)
    print (list)
    /// prints MyStruct(type: some type, message: some message, parameters: DynamicParameters(keys: ["anotherKey", "randomKey", "padlock", "fakeKey"]))

} catch {
    print(error)
    }
}

0 个答案:

没有答案