7

我有一个带有一组值的 JSON:

[
    { "tag": "Foo", … },
    { "tag": "Bar", … },
    { "tag": "Baz", … },
]

我想将此数组解码为structs 数组,其中特定类型取决于标签:

protocol SomeCommonType {}

struct Foo: Decodable, SomeCommonType { … }
struct Bar: Decodable, SomeCommonType { … }
struct Baz: Decodable, SomeCommonType { … }

let values = try JSONDecoder().decode([SomeCommonType].self, from: …)

我怎么做?目前我有这个略显丑陋的包装:

struct DecodingWrapper: Decodable {

    let value: SomeCommonType

    public init(from decoder: Decoder) throws {
        let c = try decoder.singleValueContainer()
        if let decoded = try? c.decode(Foo.self) {
            value = decoded
        } else if let decoded = try? c.decode(Bar.self) {
            value = decoded
        } else if let decoded = try? c.decode(Baz.self) {
            value = decoded
        } else {
            throw …
        }
    }
}

接着:

let wrapped = try JSONDecoder().decode([DecodingWrapper].self, from: …)
let values = wrapped.map { $0.value }

有没有更好的办法?

4

3 回答 3

6

您的数组包含有限的、可枚举的种类的异构对象;听起来像是 Swift 枚举的完美用例。它不适合多态性,因为从概念上讲,这些“事物”不一定属于同一类。他们只是碰巧被标记了。

这么看:你有一堆东西都有标签,有些是这种类型,有些是完全不同的类型,还有一些……有时你甚至不认识标签。Swift 枚举是捕捉这个想法的完美工具。

所以你有一堆结构,它们共享一个标签属性,但在其他方面完全不同:

struct Foo: Decodable {
    let tag: String
    let fooValue: Int
}

struct Bar: Decodable {
    let tag: String
    let barValue: Int
}

struct Baz: Decodable {
    let tag: String
    let bazValue: Int
}

并且您的数组可以包含上述类型或未知类型的任何实例。所以你有枚举TagggedThing(或更好的名字)。

enum TagggedThing {
    case foo(Foo)
    case bar(Bar)
    case baz(Baz)
    case unknown
}

用 Swift 术语来说,您的数组是[TagggedThing]. 所以你使TagggedThing类型符合Decodable如下:

extension TagggedThing: Decodable {
    private enum CodingKeys: String, CodingKey {
        case tag
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let tag = try container.decode(String.self, forKey: .tag)

        let singleValueContainer = try decoder.singleValueContainer()
        switch tag {
        case "foo":
            // if it's not a Foo, throw and blame the server guy
            self = .foo(try singleValueContainer.decode(Foo.self))
        case "bar":
            self = .bar(try singleValueContainer.decode(Bar.self))
        case "baz":
            self = .baz(try singleValueContainer.decode(Baz.self))
        default:
            // this tag is unknown, or known but we don't care
            self = .unknown
        }
    }
}

现在您可以解码以下 JSON:

let json: Data! = """
[
    {"tag": "foo", "fooValue": 1},
    {"tag": "bar", "barValue": 2},
    {"tag": "baz", "bazValue": 3}
]
""".data(using: .utf8)

像这样:

let taggedThings = try? JSONDecoder().decode([TagggedThing].self, from: json)
于 2017-11-08T17:17:56.547 回答
3

可能是 enum 可以使您的代码更干净。每个案例将对应于您的 json 的类型(标签)。根据情况,您会将 json 解析为适当的模型。无论如何,应该对选择哪种模型进行某种评估。所以我来到了这个

protocol SomeCommonType {}
protocol DecodableCustomType: Decodable, SomeCommonType {}

struct Foo: DecodableCustomType {}
struct Bar: DecodableCustomType {}
struct Baz: DecodableCustomType {}

enum ModelType: String {
  case foo
  case bar
  case baz

  var type: DecodableCustomType.Type {
    switch self {
    case .foo: return Foo.self
    case .bar: return Bar.self
    case .baz: return Baz.self
    }
  }
}

func decoder(json: JSON) {
  let type = json["type"].stringValue
  guard let modelType = ModelType(rawValue: type) else { return }

  // here you can use modelType.type
}
于 2017-11-04T02:52:01.387 回答
1

您还可以使用 Dictionary 进行映射:

protocol SomeCommonType {}

struct Foo: Decodable, SomeCommonType { }
struct Bar: Decodable, SomeCommonType { }
struct Baz: Decodable, SomeCommonType { }

let j: [[String:String]] = [
    ["tag": "Foo"],
    ["tag": "Bar"],
    ["tag": "Baz"],
    ["tag": "Undefined type"],
    ["missing": "tag"]
]

let mapping: [String: SomeCommonType.Type] = [
    "Foo": Foo.self,
    "Bar": Bar.self,
    "Baz": Baz.self
]

print(j.map { $0["tag"].flatMap { mapping[$0] } })
// [Optional(Foo), Optional(Bar), Optional(Baz), nil, nil]

print(j.flatMap { $0["tag"].flatMap { mapping[$0] } })
// [Foo, Bar, Baz]
于 2017-11-08T14:56:18.757 回答