Swift Codable - 可以包含不同数据类型的Parse JSON数组

时间:2018-01-18 05:58:41

标签: swift swift4 jsondecoder

我正在尝试解析一个可以

的JSON数组
{
  "config_data": [
      {
        "name": "illuminate",
        "config_title": "Blink"
      },
      {
        "name": "shoot",
        "config_title": "Fire"
      }
    ]
}

或者它可以是以下类型

{
  "config_data": [
          "illuminate",
          "shoot"
        ]
}

甚至

{
    "config_data": [
              25,
              100
            ]
  }

所以要使用JSONDecoder解析它,我创建了一个结构如下 -

Struct Model: Codable {
  var config_data: [Any]?

  enum CodingKeys: String, CodingKey {
    case config_data = "config_data"
   }

  init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    config_data = try values.decode([Any].self, forKey: .config_data)
  }
}

但是这不起作用,因为任何不能确认可解码协议。什么可以解决这个问题。该数组可以包含任何类型的数据

3 个答案:

答案 0 :(得分:4)

我使用quicktype来推断config_data的类型,并且它为您的对象,字符串和整数值建议了一个包含单独案例的枚举:

struct ConfigData {
    let configData: [ConfigDatumElement]
}

enum ConfigDatumElement {
    case configDatumClass(ConfigDatumClass)
    case integer(Int)
    case string(String)
}

struct ConfigDatumClass {
    let name, configTitle: String
}

这是the complete code example。解码enum有点棘手,但quicktype可以帮助你:

// To parse the JSON, add this file to your project and do:
//
//   let configData = try? JSONDecoder().decode(ConfigData.self, from: jsonData)

import Foundation

struct ConfigData: Codable {
    let configData: [ConfigDatumElement]

    enum CodingKeys: String, CodingKey {
        case configData = "config_data"
    }
}

enum ConfigDatumElement: Codable {
    case configDatumClass(ConfigDatumClass)
    case integer(Int)
    case string(String)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let x = try? container.decode(Int.self) {
            self = .integer(x)
            return
        }
        if let x = try? container.decode(String.self) {
            self = .string(x)
            return
        }
        if let x = try? container.decode(ConfigDatumClass.self) {
            self = .configDatumClass(x)
            return
        }
        throw DecodingError.typeMismatch(ConfigDatumElement.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ConfigDatumElement"))
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .configDatumClass(let x):
            try container.encode(x)
        case .integer(let x):
            try container.encode(x)
        case .string(let x):
            try container.encode(x)
        }
    }
}

struct ConfigDatumClass: Codable {
    let name, configTitle: String

    enum CodingKeys: String, CodingKey {
        case name
        case configTitle = "config_title"
    }
}

使用enum很高兴,因为这样可以获得最安全的类型。其他答案似乎失去了这一点。

使用quicktype的便捷初始化器选项,工作代码示例为:

let data = try ConfigData("""
{
  "config_data": [
    {
      "name": "illuminate",
      "config_title": "Blink"
    },
    {
      "name": "shoot",
      "config_title": "Fire"
    },
    "illuminate",
    "shoot",
    25,
    100
  ]
}
""")

for item in data.configData {
    switch item {
    case .configDatumClass(let d):
        print("It's a class:", d)
    case .integer(let i):
        print("It's an int:", i)
    case .string(let s):
        print("It's a string:", s)
    }
}

打印:

It's a class: ConfigDatumClass(name: "illuminate", configTitle: "Blink")
It's a class: ConfigDatumClass(name: "shoot", configTitle: "Fire")
It's a string: illuminate
It's a string: shoot
It's an int: 25
It's an int: 100

答案 1 :(得分:1)

如果出现第二个JSON,首先需要决定该怎么做。第二种JSON格式的信息较少。你想对那些丢失的数据(config_title)做什么?你真的需要它们吗?

如果你确实需要存储config_title s,那么我建议你创建一个ConfigItem结构,如下所示:

struct ConfigItem: Codable {
    let name: String
    let configTitle: String?

    init(name: String, configTitle: String? = nil) {
        self.name = name
        self.configTitle = configTitle
    }

    // encode and init(decoder:) here...
    // ...
}

实施所需的encodeinit(decoder:)方法。你知道这个演习。

现在,当您解码JSON时,像往常一样解码config_data密钥。但这一次,您可以解码为[Any],而不是使用[ConfigItem]!显然这并不总是有效,因为JSON有时可以是第二种形式。因此,您可以捕获从中抛出的任何错误,并使用config_data解码[String]。然后,将字符串数组映射到一堆ConfigItem s!

答案 2 :(得分:0)

您正在尝试JSON to objectobject to JSON?你可以试试这段代码添加任何swift文件:

extension String {
    var xl_json: Any? {
        if let data = data(using: String.Encoding.utf8) {
            return try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        }
        return nil
    }
}

extension Array {
    var xl_json: String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
            return nil
        }
        return String(data: data, encoding: .utf8)
    }
}

extension Dictionary {
    var xl_json: String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
            return nil
        }
        return String(data: data, encoding: .utf8)
    }
}

并运行此代码:

let str = "{\"key\": \"Value\"}"
let dict = str.xl_json as! [String: String] // JSON to Objc
let json = dict.xl_json                     // Objc to JSON

print("jsonStr - \(str)")
print("objc - \(dict)")
print("jsonStr - \(json ?? "nil")")

最后,你得到它:

jsonStr - {"key": "Value"}
objc - ["key": "Value"]
jsonStr - {"key":"Value"}