【问题标题】:JSONDecoder using ProtocolJSON解码器使用协议
【发布时间】:2018-05-01 03:45:00
【问题描述】:

我正在使用一个协议来创建几个结构,我使用这些结构来使用JSONDecoder 进行解码。这是我想要实现的代码示例。

protocol Animal: Codable
{
   var name: String { get }
   var age: Int { get }
}

struct Dog: Animal
{
   let name: String
   let age: Int
   let type: String
}

struct Cat: Animal
{
   let name: String
   let age: Int
   let color: String
}

以下是 dog 和 cat 的单独 JSON 有效负载:

{
    "name": "fleabag",
    "age": 3,
    "type": "big"
}

{
    "name": "felix",
    "age": 2,
    "color": "black"
}

所以当我解码 JSON 时,我不确定我会得到什么 JSON,狗还是猫。我试过这样做:

let data = Data(contentsOf: url)
let value = JSONDecoder().decode(Animal.self, from: data)

但最终会出现这个错误:

在参数类型“Animal.Protocol”中,“Animal”不符合预期的“Decodable”类型

关于解析返回Animal 实例的狗或猫的最佳方法有什么想法吗?

谢谢

【问题讨论】:

  • 狗和猫也需要 Codable 协议
  • 鉴于上面的 JSON,这是无法解决的。 JSON 中没有任何内容表明这是 Dog、Cat 还是任何其他可能符合 Animal 的无限类型。如果您知道“这是一只狗还是一只猫”,那么上面的内容是绝对可以解决的(前提是您有一个测试来确定 JSON 中的猫与狗,例如“狗有一个类型”),但不是“它是一只动物” 。”它可能是您的模块不知道的动物(可能在另一个模块中定义)。这也可以通过类型擦除来解决,但你会得到一个 AnyAnimal,而不是 Dog 或 Cat。

标签: swift protocols jsondecoder


【解决方案1】:

你将无法使用它:

let animal = try? JSONDecoder().decode(Animal.self, from: data)

解码狗或猫。它永远是动物。

如果您想将这两个 JSON 对象都解码为 Animal,则像这样定义 Animal:

struct Animal: Codable {
    var name: String
    var age: Int
}

当然,你会失去使它们成为狗 (type) 或猫 (color) 的独特元素。

【讨论】:

    【解决方案2】:

    你在这里打开了一个有点丑陋的蠕虫罐头。我理解你试图做什么,但不幸的是它在很多方面都失败了。您可以通过以下 Playground 获得一些接近您想要的结果:

    import Cocoa
    
    let dogData = """
    {
        "name": "fleabag",
        "age": 3,
        "type": "big"
    }
    """.data(using: .utf8)!
    
    let catData = """
    {
        "name": "felix",
        "age": 2,
        "color": "black"
    }
    """.data(using: .utf8)!
    
    protocol Animal: Codable
    {
        var name: String { get }
        var age: Int { get }
    }
    
    struct Dog: Animal
    {
        let name: String
        let age: Int
        let type: String
    }
    
    struct Cat: Animal
    {
        let name: String
        let age: Int
        let color: String
    }
    
    do {
        let decoder = JSONDecoder()
        let dog = try decoder.decode(Dog.self, from: dogData)
        print(dog)
        let cat = try decoder.decode(Cat.self, from: catData)
        print(cat)
    }
    
    extension Animal {
        static func make(fromJSON data: Data) -> Animal? {
            let decoder = JSONDecoder()
            do {
                let dog = try decoder.decode(Dog.self, from: data)
                return dog
            } catch {
                do {
                    let cat = try decoder.decode(Cat.self, from: data)
                    return cat
                } catch {
                    return nil
                }
            }
        }
    }
    
    if let animal = Dog.make(fromJSON: dogData) {
        print(animal)
    }
    if let animal2 = Dog.make(fromJSON: catData) {
        print(animal2)
    }
    

    但是,您会注意到有些更改是有原因的。事实上,您无法实现Decodable 方法init(from: Decoder) throws,因为它应该是chaininit 方法,而这...对于协议来说并不真正适用。我选择在 Animal.make 方法中实现你最喜欢的调度程序,但这最终也成为了一个半生不熟的解决方案。由于protocols 是元类型(也可能有充分的理由),您不能 能够在元类型上调用它们的静态方法,而必须使用具体的方法。正如Dog.make(fromJSON: catData) 行所示,这看起来很奇怪,至少可以这么说。最好将其烘焙到顶级函数中,例如

    func parseAnimal(from data:Data) {
        ...
    }
    

    但从另一个方面来看,这仍然令人不满意,因为它污染了全局命名空间。可能仍然是我们可以用可用的手段做的最好的事情。

    鉴于调度程序的丑陋,使用没有直接指示类型的 JSON 似乎是个坏主意,因为它使解析变得非常困难。但是,我看不到以真正易于解析的方式在 JSON 中传达子类型的好方法。尚未对此进行任何研究,但可能是您的下一次尝试。

    【讨论】:

      【解决方案3】:

      更好的方法是使用类而不是协议,并使用类而不是结构。您的 DogCat 类将是 Animal 的子类

      class Animal: Codable {
          let name: String
          let age: Int
      
          private enum CodingKeys: String, CodingKey {
              case name
              case age
          }
      }
      
      class Dog: Animal {
          let type: String
      
          private enum CodingKeys: String, CodingKey {
              case type
          }
      
          required init(from decoder: Decoder) throws {
              let container = try decoder.container(keyedBy: CodingKeys.self)
              self.type = try container.decode(String.self, forKey: .type)
              try super.init(from: decoder)
          }
      }
      
      class Cat: Animal {
          let color: String
      
          private enum CodingKeys: String, CodingKey {
              case color
          }
      
          required init(from decoder: Decoder) throws {
              let container = try decoder.container(keyedBy: CodingKeys.self)
              self.color = try container.decode(String.self, forKey: .color)
              try super.init(from: decoder)
          }
      }
      
      let data = Data(contentsOf: url)
      let animal = JSONDecoder().decode(Animal.self, from: data)
      

      【讨论】:

      • if animal is Dog 永远不会是真的
      • 根据您的class 声明,您可以检查if dog is Animal 以便if childClass is parentClass
      • 我了解if dog is Animal,但我不清楚if childClass is parentClass
      • @user9041624 你只能检查childClass 是一种parentClass 而不是parentClass 是一种childClass。这里DogAnimal 的孩子而不是AnimalDog 的孩子。
      • 感谢您的示例。然而@Mike Taverne 说的是真的。
      猜你喜欢
      • 2020-02-09
      • 1970-01-01
      • 2018-11-26
      • 2020-01-13
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      相关资源
      最近更新 更多