带有未知动态键的Swift 4可解码 [英] Swift 4 decodable with unknown dynamic keys

查看:110
本文介绍了带有未知动态键的Swift 4可解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON

{"DynamicKey":6410,"Meta":{"name":"","page":""}}

DynamicKey在编译时是未知的. 使用可解码的方法解析此结构.

DynamicKey is unknown at compile time.I'm trying to find a reference how to parse this struct using decodable.

public struct MyStruct: Decodable {
    public let unknown: Double
    public let meta: [String: String]

    private enum CodingKeys: String, CodingKey {
        case meta = "Meta"
    }
}

有什么想法吗?

推荐答案

要解码任意字符串,您需要这样的密钥:

To decode an arbitrary string, you need a key like this:

// Arbitrary key
private struct Key: CodingKey, Hashable, CustomStringConvertible {
    static let meta = Key(stringValue: "Meta")!

    var description: String {
        return stringValue
    }

    var hashValue: Int { return stringValue.hash }

    static func ==(lhs: Key, rhs: Key) -> Bool {
        return lhs.stringValue == rhs.stringValue
    }

    let stringValue: String
    init(_ string: String) { self.stringValue = string }
    init?(stringValue: String) { self.init(stringValue) }
    var intValue: Int? { return nil }
    init?(intValue: Int) { return nil }
}

这是一个非常通用的工具(用于static let meta),可用于各种通用密钥问题.

This is a very general-purpose tool (expect for the static let meta) that can be used for all kinds of generic-key problems.

这样,您可以找到不是.meta的第一个键,并将其用作动态键.

With that, you can find the first key that isn't .meta and use that as your dynamic key.

public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Key.self)

    meta = try container.decode([String: String].self, forKey: .meta)

    guard let dynamicKey = container.allKeys.first(where: { $0 != .meta }) else {
        throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [],
                                                                debugDescription: "Could not find dynamic key"))
    }

    unknown = try container.decode(Double.self, forKey: dynamicKey)
}


一起作为游乐场:


All together as a playground:

import Foundation

let json = Data("""
{"DynamicKey":6410,"Meta":{"name":"","page":""}}
""".utf8)

public struct MyStruct: Decodable {
    public let unknown: Double
    public let meta: [String: String]

    // Arbitrary key
    private struct Key: CodingKey, Hashable, CustomStringConvertible {
        static let meta = Key(stringValue: "Meta")!
        var description: String {
            return stringValue
        }

        var hashValue: Int { return stringValue.hash }

        static func ==(lhs: Key, rhs: Key) -> Bool {
            return lhs.stringValue == rhs.stringValue
        }

        let stringValue: String
        init(_ string: String) { self.stringValue = string }
        init?(stringValue: String) { self.init(stringValue) }
        var intValue: Int? { return nil }
        init?(intValue: Int) { return nil }
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Key.self)

        meta = try container.decode([String: String].self, forKey: .meta)

        guard let dynamicKey = container.allKeys.first(where: { $0 != .meta }) else {
            throw DecodingError.dataCorrupted(.init(codingPath: [],
                                                    debugDescription: "Could not find dynamic key"))
        }

        unknown = try container.decode(Double.self, forKey: dynamicKey)
    }
}


let myStruct = try! JSONDecoder().decode(MyStruct.self, from: json)
myStruct.unknown
myStruct.meta

该技术可以扩展为解码任意JSON .有时这样做比较容易,然后取出所需的片段,然后对每个片段进行解码.例如,使用上述JSON要点,您可以通过以下方式实现MyStruct:

This technique can be expanded to decode arbitrary JSON. Sometimes it's easier to do that, and then pull out the pieces you want, then to decode each piece. For example, with the JSON gist above, you could implement MyStruct this way:

public struct MyStruct: Decodable {
    public let unknown: Double
    public let meta: [String: String]

    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let json = try container.decode(JSON.self)

        guard let meta = json["Meta"]?.dictionaryValue as? [String: String] else {
            throw DecodingError.dataCorrupted(.init(codingPath: [],
                                                    debugDescription: "Could not find meta key"))
        }
        self.meta = meta

        guard let (_, unknownJSON) = json.objectValue?.first(where: { (key, _) in key != "Meta" }),
            let unknown = unknownJSON.doubleValue
        else {
            throw DecodingError.dataCorrupted(.init(codingPath: [],
                                                    debugDescription: "Could not find dynamic key"))
        }
        self.unknown = unknown
    }
}

这篇关于带有未知动态键的Swift 4可解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆