是否可以使用JSONDecoder解码其他参数?

时间:2018-05-01 12:57:11

标签: json swift parsing jsondecoder

我们有一些后端返回的响应:

{
    "name": "Some name",
    "number": 42,
    ............
    "param0": value0,
    "param1": value1,
    "param2": value2
}

响应的模型结构:

struct Model: Codable {
    let name: String
    let number: Int
    let params: [String: Any]
}

如何让JSONDecoder将所有未知的键值对合并到params属性中?

1 个答案:

答案 0 :(得分:2)

Decodable非常强大。它可以解码完全任意的JSON,所以这只是该问题的一个子集。有关完整解决的JSON Decodable,请参阅此JSON

我将从示例中提取Key的概念,但为简单起见,我假设值必须为IntString。您可以将parameters设为[String: JSON]并使用我的JSON解码器。

struct Model: Decodable {
    let name: String
    let number: Int
    let params: [String: Any]

    // An arbitrary-string Key, with a few "well known and required" keys
    struct Key: CodingKey, Equatable {
        static let name = Key("name")
        static let number = Key("number")

        static let knownKeys = [Key.name, .number]

        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 }
    }

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

        // First decode what we know
        name = try container.decode(String.self, forKey: .name)
        number = try container.decode(Int.self, forKey:. number)

        // Find all the "other" keys
        let optionalKeys = container.allKeys
            .filter { !Key.knownKeys.contains($0) }

        // Walk through the keys and try to decode them in every legal way
        // Throw an error if none of the decodes work. For this simple example
        // I'm assuming it is a String or Int, but this is also solvable for
        // arbitarily complex data (it's just more complicated)
        // This code is uglier than it should be because of the `Any` result.
        // It could be a lot nicer if parameters were a more restricted type
        var p: [String: Any] = [:]
        for key in optionalKeys {
            if let stringValue = try? container.decode(String.self, forKey: key) {
                p[key.stringValue] = stringValue
            } else {
                 p[key.stringValue] = try container.decode(Int.self, forKey: key)
            }
        }
        params = p
    }
}

let json = Data("""
{
    "name": "Some name",
    "number": 42,
    "param0": 1,
    "param1": "2",
    "param2": 3
}
""".utf8)

try JSONDecoder().decode(Model.self, from: json)
// Model(name: "Some name", number: 42, params: ["param0": 1, "param1": "2", "param2": 3])

其他想法

我认为下面的评论非常重要,未来的读者应该仔细看看。我想说明需要多少代码重复,以及可以轻松提取和重用多少代码,这样就不需要任何魔术或动态功能。

首先,提取常见且可重复使用的部分:

func additionalParameters<Key>(from container: KeyedDecodingContainer<Key>,
                               excludingKeys: [Key]) throws -> [String: Any]
    where Key: CodingKey {
        // Find all the "other" keys and convert them to Keys
        let excludingKeyStrings = excludingKeys.map { $0.stringValue }

        let optionalKeys = container.allKeys
            .filter { !excludingKeyStrings.contains($0.stringValue)}

        var p: [String: Any] = [:]
        for key in optionalKeys {
            if let stringValue = try? container.decode(String.self, forKey: key) {
                p[key.stringValue] = stringValue
            } else {
                p[key.stringValue] = try container.decode(Int.self, forKey: key)
            }
        }
        return p
}

struct StringKey: CodingKey {
    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 }
}

现在,Model的解码器已缩减为

struct Model: Decodable {
    let name: String
    let number: Int
    let params: [String: Any]

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

        name = try container.decode(String.self, forKey: StringKey("name"))
        number = try container.decode(Int.self, forKey: StringKey("number"))
        params = try additionalParameters(from: container,
                                          excludingKeys: ["name", "number"].map(StringKey.init))
    }
}

如果有一种神奇的方式可以说“请以默认的方式处理这些属性”,那将是很好的,但我不太清楚这看起来像坦率地说。这里的代码量与实现NSCoding的代码量大致相同,远远低于实现NSJSONSerialization的代码量,如果它太繁琐,很容易交给swiftgen(这基本上就是你需要的代码)写为init)。作为交换,我们得到了完整的编译时类型检查,因此我们知道当我们遇到意外情况时它不会崩溃。

有几种方法可以使上面的内容更短(我现在正在考虑涉及KeyPaths的想法,以使其更加方便)。关键是当前的工具非常强大,值得探索。