【问题标题】:Swift 4 Decodable - decoding JSON object into `Data`Swift 4 Decodable - 将 JSON 对象解码为“数据”
【发布时间】:2018-04-10 11:28:31
【问题描述】:

我有以下数据结构:

{
    "type": "foo"
    "data": { /* foo object */ }
}

这是我的解码类:

final public class UntypedObject: Decodable {

    public var data: Data

    enum UntypedObjectKeys: CodingKey {
        case data
    }

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

        self.data = try values.decode(Data.self, forKey: .data)
    }
}

我正在获取此类对象的数组,这就是我对其进行解码的方式:

let decoder = JSONDecoder()
let objectList = try decoder.decode([UntypedObject].self, from: data)

但是我在控制台中收到此错误:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), Playground_Sources.UntypedObject.UntypedObjectKeys.data], debugDescription: "期望解码 Array 但找到了字典。",底层错误: nil))

所以问题是是否有可能将正确的 JSON 对象解码为 Data 类型属性,如果是,我该如何实现?

【问题讨论】:

  • 请向我们展示您的 JSON 输入数据。根据您收到的错误(即,“应解码 Array 但找到了 Dictionary。”)您的 JSON 格式可能不是您所期望的。
  • @PauloMattos - 这就是重点。我希望将“数据”键下的所有内容解码为Data。不管是dict、数组、数字还是字符串。
  • 您想要”data" 键下的原始数据,无论格式如何?如果是这样,看起来很棘手...... ;)
  • 是的,纯字节。
  • 您不能在 json 字符串中发送纯数据。您将需要使用 base64 编码。除此之外,如果您没有提供有效的 json 以用作您的问题的参考,那将无法提供帮助。

标签: swift4 decodable


【解决方案1】:

这对于 OP 来说可能为时已晚,但我遇到了类似的问题,需要解决方案。 希望这对其他人有用。

对于我的问题,我想使用Decodable 来解码我的 JSON 使用 Swift 5.1。然而,在我的对象层次结构的各个点,我想返回一个不支持Decodable,但支持从(非平凡的)JSON 字符串解码的 objC 对象(来自第三方库)。我通过使用JSONSerialization 创建一个无类型的对象层次结构解决了这个问题,我可以从解码器的userInfo 属性中检索并使用解码器的contextPath 搜索以找到我的数据,然后使用JSONSerialization 来 将其转换回字符串数据。

此解决方案不假设获取具有“数据”键的对象所需的对象/数组层次结构。

// Swift 5.1 Playground
import Foundation

// Input configuration JSON
let jsonStr = """
{
  "foo":"bar",
  "bars": [
    {
      "data":{
        "thing1":"#111100",
        "thing2":12
      }
    },
    {
      "data":{
        "thing1":"#000011",
        "thing2":64.125
      }
    }
  ]
}
"""

// Object passed to the decoder in the UserInfo Dictionary
// This will contain the serialized JSON data for use by
// child objects
struct MyCodingOptions {
  let json: Any

  static let key = CodingUserInfoKey(rawValue: "com.unique.mycodingoptions")!
}

let jsonData = Data(jsonStr.utf8)
let json = try JSONSerialization.jsonObject(with: jsonData)
let options = MyCodingOptions(json: json)

let decoder = JSONDecoder()
decoder.userInfo = [MyCodingOptions.key: options]

// My object hierarchy
struct Root: Decodable {
  let foo: String
  let bars: [Bar]
}

struct Bar: Decodable {
  let data: Data?

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

// Implement a custom decoder for Bar
// Use the context path and the serialized JSON to get the json value
// of "data" and then deserialize it back to data.
extension Bar {
  init(from decoder: Decoder) throws {
    var data: Data? = nil
    if let options = decoder.userInfo[MyCodingOptions.key] as? MyCodingOptions {
      // intialize item to the whole json object, then mutate it down the "path" to Bar
      var item: Any? = options.json
      let path = decoder.codingPath // The path to the current object, does not include self
      for key in path {
        if let intKey = key.intValue {
          //array
          item = (item as? [Any])?[intKey]
        } else {
          //object
          item = (item as? [String:Any])?[key.stringValue]
        }
      }
      // item is now Bar, which is an object (Dictionary)
      let bar = item as? [String:Any]
      let dataKey = CodingKeys.data.rawValue
      if let item = bar?[dataKey] {
        data = try JSONSerialization.data(withJSONObject: item)
      }
    }
    self.init(data: data)
  }
}

if let root = try? decoder.decode(Root.self, from: jsonData) {
  print("foo: \(root.foo)")
  for (i, bar) in root.bars.enumerated() {
    if let data = bar.data {
      print("data #\(i): \(String(decoding: data, as: UTF8.self))")
    }
  }
}

//prints:
// foo: bar
// data #0: {"thing2":12,"thing1":"#111100"}
// data #1: {"thing2":64.125,"thing1":"#000011"}

【讨论】:

    【解决方案2】:

    为你的错误特别改变

    let objectList = try decoder.decode([UntypedObject].self, from: data)
    

    let objectList = try decoder.decode(UntypedObject.self, from: data)
    

    会修复它(但我仍然认为您无法将 JSON 上的“数据”键的内容作为数据获取。)

    您的错误原因是因为您的 JSON 响应包含一个对象作为根,该对象在 Swift 中被视为字典(因为键/值映射),但您试图解码一个对象数组。

    【讨论】:

      【解决方案3】:

      在解码的时候,能不能先检查一下是不是Array?

      如果“true”,则上面的代码有效,否则为字典解码

      查看这篇我觉得很有帮助的关于解码的文章:

      https://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375

      【讨论】:

      • 您好,欢迎来到 SO!您能否向我们展示一个代码示例以帮助您进一步回答有用的问题?谢谢!
      猜你喜欢
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多