首页 > 解决方案 > 如何使用包含已编码值的 Encodable 在 Swift 中编码结构

问题描述

想象一个如下的数据结构,其中包含contents一个已编码的 JSON 片段的值。

let partial = """
{ "foo": "Foo", "bar": 1 }
"""

struct Document {
  let contents: String
  let other: [String: Int]
}

let doc = Document(contents: partial, other: ["foo": 1])

期望的输出

组合数据结构应按contents原样使用并进行编码other

{
  "contents": { "foo": "Foo", "bar": 1 },
  "other": { "foo": 1 }
}

使用Encodable

以下实现Encodable编码Document为 JSON,但它也重新编码contents为字符串,这意味着它被包裹在引号中,并且所有"引号都转义为\".

extension Document : Encodable {
    enum CodingKeys : String, CodingKey {
        case contents
        case other
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(contents, forKey: .contents)
        try container.encode(other, forKey: .other)
    }
}

输出

{
  "contents": "{\"foo\": \"Foo\", \"bar\": 1}",
  "other": { "foo": 1 }
}

怎么可能encode就这样通过contents

标签: jsonswiftencodingcodableencodable

解决方案


我同意艾哈迈德的基本方法,但我假设你需要一些更有活力的东西。在这种情况下,您应该明确这content不是“字符串”。它是 JSON。因此,您可以使用JSON 类型将其存储为 JSON (在此处进行了简化,请参阅 gist 以获取功能更丰富的版本):

enum JSON: Codable {
    struct Key: CodingKey, Hashable, CustomStringConvertible {
        var description: String {
            return 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 }
    }

    case string(String)
    case number(Double) // FIXME: Split Int and Double
    case object([Key: JSON])
    case array([JSON])
    case bool(Bool)
    case null

    init(from decoder: Decoder) throws {
        if let string = try? decoder.singleValueContainer().decode(String.self) { self = .string(string) }
        else if let number = try? decoder.singleValueContainer().decode(Double.self) { self = .number(number) }
        else if let object = try? decoder.container(keyedBy: Key.self) {
            var result: [Key: JSON] = [:]
            for key in object.allKeys {
                result[key] = (try? object.decode(JSON.self, forKey: key)) ?? .null
            }
            self = .object(result)
        }
        else if var array = try? decoder.unkeyedContainer() {
            var result: [JSON] = []
            for _ in 0..<(array.count ?? 0) {
                result.append(try array.decode(JSON.self))
            }
            self = .array(result)
        }
        else if let bool = try? decoder.singleValueContainer().decode(Bool.self) { self = .bool(bool) }
        else if let isNull = try? decoder.singleValueContainer().decodeNil(), isNull { self = .null }
        else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [],
                                                                       debugDescription: "Unknown JSON type")) }
    }

    func encode(to encoder: Encoder) throws {
        switch self {
        case .string(let string):
            var container = encoder.singleValueContainer()
            try container.encode(string)
        case .number(let number):
            var container = encoder.singleValueContainer()
            try container.encode(number)
        case .bool(let bool):
            var container = encoder.singleValueContainer()
            try container.encode(bool)
        case .object(let object):
            var container = encoder.container(keyedBy: Key.self)
            for (key, value) in object {
                try container.encode(value, forKey: key)
            }
        case .array(let array):
            var container = encoder.unkeyedContainer()
            for value in array {
                try container.encode(value)
            }
        case .null:
            var container = encoder.singleValueContainer()
            try container.encodeNil()
        }
    }
}

有了它,您可以重新定义您的文档以保存 JSON:

struct Document: Codable {
  let contents: JSON
  let other: [String: Int]
}

如果您愿意,可以从字符串中解码 JSON:

let doc = Document(contents:
    try! JSONDecoder().decode(JSON.self, from: Data(partial.utf8)),
                   other: ["foo": 1])

有了它,默认值JSONEncoder()就是您获取所描述的输出所需的全部内容。


推荐阅读