动态JSON解码Swift 4

时间:2017-12-02 01:20:43

标签: json swift dynamic decodable

我试图在Swift 4中解码以下JSON:

{
    "token":"RdJY3RuB4BuFdq8pL36w",
    "permission":"accounts, users",
    "timout_in":600,
    "issuer": "Some Corp",
    "display_name":"John Doe",
    "device_id":"uuid824fd3c3-0f69-4ee1-979a-e8ab25558421"
}

问题是,JSON中的最后2个元素(display_namedevice_id)可能存在也可能不存在,或者元素可能被命名为完全不同但仍未知的元素,即{{1} }

所以我想要实现的是解码已知的内容,即"fred": "worker", "hours" : 8tokenpermissiontimeout_in以及任何其他元素({{ 1}},issuer等)将它们放入字典中。

我的结构如下:

display_name

能够解码JSON可能包含动态信息的已知结构的某些部分,如果有人能提供一些指导,我可以在这里解决。

由于

2 个答案:

答案 0 :(得分:5)

受到@matt评论的启发,这是我已经完整的样本。我扩展了KeyedDecodingContainer以解码未知密钥,并提供一个参数来过滤掉已知的CodingKeys

示例JSON

{
    "token":"RdJY3RuB4BuFdq8pL36w",
    "permission":"accounts, users",
    "timout_in":600,
    "issuer": "Some Corp",
    "display_name":"John Doe",
    "device_id":"uuid824fd3c3-0f69-4ee1-979a-e8ab25558421"
}

Swift结构

struct AccessInfo : Decodable
{
    let token: String
    let permission: [String]
    let timeout: Int
    let issuer: String
    let additionalData: [String: Any]

    private enum CodingKeys: String, CodingKey
    {
        case token
        case permission
        case timeout = "timeout_in"
        case issuer
    }

    public init(from decoder: Decoder) throws
    {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        token = container.decode(String.self, forKey: .token)
        permission = try container.decode(String.self, forKey: .permission).components(separatedBy: ",")
        timeout = try container.decode(Int.self, forKey: . timeout)
        issuer = container.decode(String.self, forKey: .issuer)

        // Additional data decoding
        let container2 = try decoder.container(keyedBy: AdditionalDataCodingKeys.self)
        self.additionalData = container2. decodeUnknownKeyValues(exclude: CodingKeys.self)
    }
}

private struct AdditionalDataCodingKeys: CodingKey
{
    var stringValue: String
    init?(stringValue: String)
    {
        self.stringValue = stringValue
    }

    var intValue: Int?
    init?(intValue: Int)
    {
        return nil
    }
}

KeyedDecodingContainer Extension

extension KeyedDecodingContainer where Key == AdditionalDataCodingKeys
{
    func decodeUnknownKeyValues<T: CodingKey>(exclude keyedBy: T.Type) -> [String: Any]
    {
        var data = [String: Any]()

        for key in allKeys
        {
            if keyedBy.init(stringValue: key.stringValue) == nil
            {
                if let value = try? decode(String.self, forKey: key)
                {
                    data[key.stringValue] = value
                }
                else if let value = try? decode(Bool.self, forKey: key)
                {
                    data[key.stringValue] = value
                }
                else if let value = try? decode(Int.self, forKey: key)
                {
                    data[key.stringValue] = value
                }
                else if let value = try? decode(Double.self, forKey: key)
                {
                    data[key.stringValue] = value
                }
                else if let value = try? decode(Float.self, forKey: key)
                {
                    data[key.stringValue] = value
                }
                else
                {
                    NSLog("Key %@ type not supported", key.stringValue)
                }
            }
        }

        return data
    }
}

致电代码

let decoder = JSONDecoder()
let accessInfo = try decoder.decode(AccessInfo.self, from: data!)

print("Token: \(accessInfo.token)")
print("Permission: \(accessInfo.permission)")
print("Timeout: \(accessInfo.timeout)")
print("Issuer: \(accessInfo.issuer)")
print("Additional Data: \(accessInfo.additionalData)")

<强>输出

Token: RdJY3RuB4BuFdq8pL36w
Permission: ["accounts", "users"]
Timeout: 600
Issuer: "Some Corp"
Additional Data: ["display_name":"John Doe", "device_id":"uuid824fd3c3-0f69-4ee1-979a-e8ab25558421"]

答案 1 :(得分:1)

问题实际上是Swift 4 Decodable with keys not known until decoding time的副本。一旦你理解了构建一个最底层的最小CodingKey采用者结构作为编码密钥的技巧,你可以将它用于任何字典。

在这种情况下,您可以使用键控容器的allKeys来获取未知的JSON字典键。

为了演示,我将仅限于JSON字典中完全未知的部分。想象一下这个JSON:

let j = """
{
    "display_name":"John Doe",
    "device_id":"uuid824fd3c3-0f69-4ee1-979a-e8ab25558421"
}
"""
let jdata = j.data(using: .utf8)!

假设我们不知道该字典中的内容,除了它具有字符串键和字符串值之外。所以我们想要解析jdata而不知道它的键是什么。

因此,我们有一个由一个字典属性组成的结构:

struct S {
    let stuff : [String:String]
}

现在的问题是如何将JSON解析为该结构 - 即,如何使该结构符合Decodable并处理该JSON。

以下是:

struct S : Decodable {
    let stuff : [String:String]
    private struct CK : CodingKey {
        var stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        var intValue: Int?
        init?(intValue: Int) {
            return nil
        }
    }
    init(from decoder: Decoder) throws {
        let con = try! decoder.container(keyedBy: CK.self)
        var d = [String:String]()
        for key in con.allKeys {
            let value = try! con.decode(String.self, forKey:key)
            d[key.stringValue] = value
        }
        self.stuff = d
    }
}

现在我们解析:

let s = try! JSONDecoder().decode(S.self, from: jdata)

我们得到一个S实例,stuff就是这个字典:

["device_id": "uuid824fd3c3-0f69-4ee1-979a-e8ab25558421", "display_name": "John Doe"]

这就是我们想要的结果。