【问题标题】:Swift Codable reusing a subset of keys shared across different models Struct/ClassSwift Codable 重用跨不同模型结构/类共享的键子集
【发布时间】:2021-05-22 18:32:36
【问题描述】:

我想知道是否有一种可行的方法可以通过使用自定义解码器初始化程序和/或多个容器和 Codingkeys 在多个模型之间共享公共属性。这是我想映射到相应的可编码模型的 JSON 对象:

JSON Object

我想映射到 Codable 的属性是“sprites”。

如您所见,back_default、back_female 等许多属性。 可以在其他模型之间共享,例如 sprites->other->dream_world、sprites->other- >official-artwork 和 sprites->versions->generation-i->red-blue

我的目标是能够使用一个共享模型并自定义他的解码器(可能通过使用多个容器),因此我可以说例如:如果当前要解码的密钥是“official-artwork" 仅解码此模型对象公开的所有 CodingKeys 的子集(也许我需要使用另一个子容器?)所以我将只有 1 个解码字段用于密钥 official-artwork, dream-world 等键的 2 个解码字段。

[编辑]

目前我想出 other 键的解决方案是这样的,但是某些属性是共享的,我认为有更好的解决方案(如果我理解我可以正确地做到这一点,我可以将其应用于模型的 versions 键):

struct PokemonSpritesModel: Codable {
   
   
   //MARK: Properties
   
   var back_default: String?
   var back_female: String?
   var back_shiny: String?
   var back_shiny_female: String?
   var front_default: String?
   var front_female: String?
   var front_shiny: String?
   var front_shiny_female: String?
   
   var other: PokemonSpritesModelOther?
   var versions: PokemonSpritesModelVersions?
   
   
}


struct PokemonSpritesModelOther: Codable {
   
   //MARK: Properties
   
   var dreamWorld: PokemonSpritesModelOtherDreamWorld?
   var officialArtwork: PokemonSpritesModelOtherOfficialArtwork?
   
   
   private enum CodingKeys: String, CodingKey {
      case officialArtwork = "official-artwork", dreamWorld = "dream_world"
   }

   
   
   struct PokemonSpritesModelOtherDreamWorld: Codable {
      
      //MARK: Properties
      
      var front_default: String?
      var front_female: String?
      
   }
   
   
   struct PokemonSpritesModelOtherOfficialArtwork: Codable {
      
      //MARK: Properties
      
      var front_default: String?
      
   }
   
}

我可以使用之前的模型并将其扩展为所有其他 json 对象来表示,但是要编写很多重复的代码,我认为有比我目前正在做的更好的方法。我已经阅读了很多 SO 和中型博客文章,但它们没有帮助我。

我不确定我的要求是否可以在 Swift 中完成。

[编辑 2]

我认为最好从头开始,让其他人了解我想要完成的工作。目前我对该 JSON 结构的 Codable 是这样的:

struct PokemonDetailsModel: Decodable {
   
   
   // MARK: Properties
   
   var name: String?
   var base_experience: Int?
   var order: Int?
   var sprites: PokemonSpritesModel?
   var stats: [PokemonStatsModel]?
   var types: [PokemonTypesModel]?
   
}


struct PokemonSpritesModel: Decodable {
   
   
   //MARK: Properties

   // ======== SET Of keys that are repeated

   var back_default: String?
   var back_female: String?
   var back_shiny: String?
   var back_shiny_female: String?
   var front_default: String?
   var front_female: String?
   var front_shiny: String?
   var front_shiny_female: String?

   // ======== SET Of keys that are repeated
   
   var other: PokemonSpritesModelOther?
   var versions: PokemonSpritesModelVersions?
   
   
}

struct PokemonSpritesModelOther: Decodable {
   
   //MARK: Properties
   var dreamWorld: PokemonSpritesModelOtherDreamWorld?
   var officialArtwork: PokemonSpritesModelOtherOfficialArtwork?
   
   
   
   private enum CodingKeys: String, CodingKey {
      case officialArtwork = "official-artwork", dreamWorld = "dream_world"
   }
   
   struct PokemonSpritesModelOtherDreamWorld: Decodable {
      
      //MARK: Properties
      var front_default: String?
      var front_female: String?
      
   }
   
   
   struct PokemonSpritesModelOtherOfficialArtwork: Decodable {
      
      //MARK: Properties
      var front_default: String?
      
   }
   
}

struct PokemonSpritesModelVersions: Decodable {
   
   
   //MARK: Properties
   var generation_i: PokemonSpritesModelVersionsGenerationsI?
   var generation_ii: PokemonSpritesModelVersionsGenerationsII?
   //   var generation_iii: PokemonSpritesModelVersionsGenerationsIII?
   //   var generation_iv: PokemonSpritesModelVersionsGenerationsIV?
   //   var generation_v: PokemonSpritesModelVersionsGenerationsV?
   //   var generation_vi: PokemonSpritesModelVersionsGenerationsVI?
   //   var generation_vii: PokemonSpritesModelVersionsGenerationsVII?
   //   var generation_viii: PokemonSpritesModelVersionsGenerationsVIII?
   
   
   
   private enum CodingKeys: String, CodingKey {
      case generation_i = "generation-i",
                  generation_ii = "generation-ii",
      //           generation_iii = "generation-iii",
      //           generation_iv = "generation-iv",
      //           generation_v = "generation-v",
      //           generation_vi = "generation-vi",
      //           generation_vii = "generation-vii",
      //           generation_viii = "generation-viii"
   }
   
   
   struct PokemonSpritesModelVersionsGenerationsI: Decodable {
      
      //MARK: Properties
      
      var red_blue: PokemonSpritesModelVersionsGenerationsColors?
      var yellow: PokemonSpritesModelVersionsGenerationsColors?
      
      private enum CodingKeys: String, CodingKey {
         case red_blue = "red-blue", yellow
      }
      
   }
   
   
   struct PokemonSpritesModelVersionsGenerationsII: Decodable {
      
      //MARK: Properties
      var crystal: PokemonSpritesModelVersionsGenerationsColors?
      var gold: PokemonSpritesModelVersionsGenerationsColors?
      var silver: PokemonSpritesModelVersionsGenerationsColors?
   }



   struct  PokemonSpritesModelVersionsGenerationsColors: Decodable {
      

      //****** Notes: Some of the keys here (i marked them with an asterisk) are not part of the Set of keys market in the 'sprites' json object that are shared across different models

      var back_default: String?
      var back_shiny: String?
      var back_gray: String? // *
      var back_female: String?
      var back_shiny_female: String?
      var front_default: String?
      var front_shiny: String?
      var front_gray: String? // *
      var front_female: String?
      var front_shiny_female: String?
      
   }

我省略了其他代结构,因为概念是相同的。

使用这种方法,一切正常,但问题是我始终使用结构“PokemonSpritesModelVersionsGenerationsColors”中的完整键集(我也应该使用“精灵”的键集,但我不知道如何推断 Set 并使 sprites 结构仍然工作,另外我还应该在“PokemonSpritesModelVersionsGenerationsColors”中添加标有 * 的新灰色)。

正如你所说,重复几种类型的键是 sprites 结构的子集(应排除 other 和 versions json 对象,但正如我之前所说,应添加标有 * 的精灵)。

根据我所做的研究,有两种可能的解决方案可以完成我想做的事情:

  1. 创建一个单独的 DTO 层(代表服务器 API 返回的数据的模型),然后创建另一个 域层(应用程序的模型)。每个域模型将过滤相应 DTO 模型的键集,因此域层模型将匹配服务器响应(DTO 模型与服务器响应不匹配,因为它不会仅使用必要子集的必需键)

  2. 使用自定义解码器初始化程序 + 多容器的某种组合,通过编码键子类型枚举(可能借助枚举关联值)+ 可能还有其他东西。

我想避免第一种方法,主要是因为有两个层,除了域模型中包含的字段和业务逻辑以过滤必要的键之外,它们几乎是相同的。我正在考虑继续使用 2 方法。

我想我有一个想法,但我不能把所有的部分放在一起。我主要是在阅读这些博客文章:

  1. https://matteomanferdini.com/codable/
  2. https://lostmoa.com/blog/CodableConformanceForSwiftEnumsWithMultipleAssociatedValuesOfDifferentTypes/
  • 其他资源
  1. 使用关联值仅解码键的子集? (https://forums.swift.org/t/codable-synthesis-for-enums-with-associated-values/41493)
  2. 多个容器用作鉴别器以仅解码键的子集? (https://forums.swift.org/t/automatic-codable-conformance-for-enums-with-associated-values-that-themselves-conform-to-codable/11499)
  3. 检查解码器当前正在解码什么类型的密钥并仅创建该密钥? https://stackoverflow.com/a/53270057/2685716)
  4. 多个容器? (https://stackoverflow.com/a/57788293/2685716)

我认为第 1 篇和第 2 篇博文是我可以从中获得一些想法来构建这个 sprites Json Codable stuct 的一篇。从 1 篇博文中,这可能是更有趣的代码部分:

extension Launch: Decodable {
    enum CodingKeys: String, CodingKey {
        case timeline
        case links
        case rocket
        case flightNumber = "flight_number"
        case missionName = "mission_name"
        case date = "launch_date_utc"
        case succeeded = "launch_success"
        case launchSite = "launch_site"
        
        enum RocketKeys: String, CodingKey {
            case rocketName = "rocket_name"
        }
        
        enum SiteKeys: String, CodingKey {
            case siteName = "site_name_long"
        }
        
        enum LinksKeys: String, CodingKey {
            case patchURL = "mission_patch"
        }
    }
}

从 2 篇博客文章中,这可能是我正在寻找的代码,它从顶部/根键(我们的 sprites json 对象?)开始,一直到我们需要的 Json 对象的底部解码。

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let key = container.allKeys.first
    
    switch key {
    case .empty:
        self = .empty
    case .editing:
        let subview = try container.decode(
            EditSubview.self,
            forKey: .editing
        )
        self = .editing(subview: subview)
    case .exchangeHistory:
        let connection = try container.decode(
            Connection?.self,
            forKey: .exchangeHistory
        )
        self = .exchangeHistory(connection: connection)
    case .list:
        var nestedContainer = try container.nestedUnkeyedContainer(forKey: .list)
        let selectedId = try nestedContainer.decode(UUID.self)
        let expandedItems = try nestedContainer.decode([Item].self)
        self = .list(
            selectedId: selectedId,
            expandedItems: expandedItems
        )
    default:
        throw DecodingError.dataCorrupted(
            DecodingError.Context(
                codingPath: container.codingPath,
                debugDescription: "Unabled to decode enum."
            )
        )
    }
}

所以我将尝试以最简单的方式总结我想要做的事情:我的想法是创建多个容器(其中一些将是嵌套容器,可能是无键容器)属于全局的键子集在不同模型之间共享的密钥集。比在同一个结构中或者在分离结构中更好(也许我还需要在其中移动与之关联的枚举键的子集)我将有一个自定义解码器初始化程序,它将仅创建在这个枚举子集中定义的键键)。

[编辑 3]

@RobNapier 是的,我想使用相同的语法。我仍然不知道什么是最简单或正确的方法。您能否提供一个完整的示例以及您的 [String:URL] 方法,例如,使我能够通过重用共享密钥来解码以下 json?

{
  "sprites": 
  {
    "back_default": "some text",
    "back_female": "some text",
    "back_shiny": "some text",
    "back_shiny_female": "some text",
    "front_default": "some text",
    "front_female": "some text",
    "front_shiny": "some text",
    "front_shiny_female": "some text",
    "other": {
        "dream_world": {
          "front_default": "some text",
          "front_female": "some text"
        }, 
        "official-artwork": {
          "front_female": "some text"
        }
    }
  }

}

【问题讨论】:

  • 请您分享一些您迄今为止尝试过的代码,或者提供更多解释?
  • 请尝试检查这个答案:stackoverflow.com/a/66275895/7119329 它回答了你的问题吗?
  • 这看起来很可行,但不清楚您希望最终的 API 是什么样子。您是想说“仅解码other/official-artwork 版本并返回给我一个Sprite”,还是说“解码整个内容,然后我将查询other/official-artwork”?您希望“dream_world”和“official-artwork”成为硬编码类型,还是这些恰好位于other 下的真正动态键? other 键在这里很重要,还是你想把它弄平?基本上,如果您可以拥有任何东西,您希望这是什么最终结构?
  • 您想要使用语法pokemonmodel.sprites.other.dream_world.front_default吗?这与数据的结构化方式密切相关。你真的想要.other. 吗?在[String:URL] 字典上构建它,而不是这么多的自定义结构,这使得它变得更加简单。显式 PokemonSpritesModelOtherOfficialArtwork 结构(以及更多手工构建的结构)的价值是什么?在我的回答中,所有这些都只是 Sprite,并且允许 Sprite 嵌套。
  • 我的答案正是你所描述的,一步一步。查看我在顶部提供的示例 JSON,在底部提供用于读取它的语法以及将字段映射到 URL 的 urls 字典。我添加了一个完整运行版本的链接

标签: json swift codable


【解决方案1】:

有很多方法可以做到这一点,具体取决于您希望该对象具有哪种接口,但这里有一种方法。完成后,您将能够引用sprites.frontShiny 以获取front_shiny 的默认URL,并且您将能够使用sprites[.official].frontDefault 之类的下标获取变体。我希望你会想要稍微调整这个实现以匹配你的使用,但它应该让你开始。

我们正在解码的结构如下所示:

{
  ...
  "sprites": {
    "back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/21.png",
    "back_female": null,
    "back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/21.png",
    "back_shiny_female": null,
    "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/21.png",
    "front_female": null,
    "front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/21.png",
    "front_shiny_female": null,
    "other": {
      "dream_world": {
        "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/21.svg",
        "front_female": null
      },
      "official-artwork": {
        "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/21.png"
      }
    },
    "versions": {
      "generation-i": {
        "red-blue": {
          "back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-i/red-blue/back/21.png",
          "back_gray": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-i/red-blue/back/gray/21.png",
          "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-i/red-blue/21.png",
          "front_gray": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-i/red-blue/gray/21.png"
        },
...

需要注意的重要一点是,Sprite 结构会重复多次,首先是在根级别,然后在诸如“other/dream_world”和“versions/generation-i”等路径下的各个嵌套点/red-blue”(见PokeAPI/sprites)。

我的假设是您不太关心“其他”和“版本/第 i 代”层,并且真的只想谈论特定的变体,例如 .dreamWorld 和 .redBlue。 (这可以适应暴露那些其他层,但当前的实现有意隐藏它们。)

第一个工具是来自Swift 4 decodable with unknown dynamic keys的工具,用于解码的任意字符串键:

struct AnyStringKey: CodingKey, Hashable, CustomStringConvertible {
    var stringValue: String = ""
    var intValue: Int?
    init?(stringValue: String) { self.stringValue = stringValue }
    init?(intValue: Int) {}
}

另一个关键工具将是用于存储的[String: URL],变体将像 Unix 路径一样存储:other/official-artwork/...。

从解码开始:

struct Sprites {
   var urls: [String: URL] = [:]
}

extension Sprites: Decodable {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: AnyStringKey.self)

        // Recursively decode, placing any URLs at this layer, and prepending
        // the current key to the path for child layers. Note that this
        // ignores all errors. If the data is malformed, then the dictionary
        // will just be empty.
        for key in container.allKeys {
            if let value = try? container.decode(URL.self, forKey: key) {
                urls[key.stringValue] = value
            } else if let variant = try? container.decode(Sprites.self, forKey: key) {
                for (childKey, value) in variant.sprites {
                    urls["\(key.stringValue)/\(childKey)"] = value
                }
            }
        }
    }
}

有了这个,你可以按键访问数据:

// https://pokeapi.co/docs/v2
struct Pokemon: Decodable {
    let sprites: Sprites
}

let sprites = try JSONDecoder().decode(Pokemon.self, from: json).sprites
print(sprites.urls["front_default"]!)

没关系,但使用起来有点不方便。我们可以通过一些计算属性来改进它。

extension Sprites {
    var frontDefault: URL? { urls["front_default"] }
    var frontShiny: URL? { urls["front_shiny"] }
    var frontFemale: URL? { urls["front_female"] }
    var frontShinyFemale: URL? { urls["front_shiny_female"] }
    var backDefault: URL? { urls["back_default"] }
    var backShiny: URL? { urls["back_shiny"] }
    var backFemale: URL? { urls["back_female"] }
    var backShinyFemale: URL? { urls["back_shiny_female"] }
}

还可以从urls 字典中访问较低级别:

print(sprites.urls["other/official-artwork/front_default"]!)

但同样,这很不方便。我们可以使用 Variant 下标做得更好。

struct Variant: Hashable, CustomStringConvertible {
    let stringValue: String
    init(_ stringValue: String) { self.stringValue = stringValue }
    var description: String { stringValue }

    static var official: Variant { Variant("other/official-artwork/") }
    static var dreamWorld: Variant { Variant("other/dream_world/") }
    static var redBlue: Variant { Variant("versions/generation-i/red-blue/")}
}

还有一个重写字典的下标,从键中删除变体前缀,并删除任何缺少该前缀的内容:

extension Sprites {
    subscript(variant: Variant) -> Sprites {
        let prefix = variant.stringValue

        return Sprites(urls: urls.reduce(into: [:]) { (dict, kv) in
            let (key, value) = kv
            if key.hasPrefix(prefix) {
                let newKey = String(key.dropFirst(prefix.count))
                dict[newKey] = value
            }
        })
    }
}

这允许您从现有的 Sprite 中提取新的 Sprite:

let official = sprites[.official]
print(official.frontDefault!)

Full Gist

【讨论】:

  • 非常感谢您的快速回复,明天我会花时间仔细阅读并给您一个正确的答案;)
  • 关于您的回答,我仍在尝试了解您使用的方法类型,您能否给我一个简单的示例,以遵循整体方法,仅从 sprites json 对象创建解码部分到 dream_world json 对象的键?另外为什么你使用一个函数来删除变体前缀?
  • 我已经更新了我的问题并提供了更多详细信息
  • 我只需要了解如何创建整个可解码结构,例如从口袋妖怪模型中的 sprites json 对象到具有共享键子集的其他对象之一 + 可能是其他键不是子集的一部分。如果我了解如何为这个单一的树流做到这一点,我可以将相同的想法复制到精灵 json 树的其他分支
  • "你为什么使用函数来删除变体前缀?"这样当您访问model.sprites[.official] 时,您会返回一个 Sprite,您可以直接访问它的属性(因为它的 URL 现在是顶级的)。我认为你在这里制作了太多的结构。整个精灵树只是tag->URL的嵌套字典,IMO应该这样对待。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 2019-05-12
  • 1970-01-01
  • 2013-01-11
  • 2014-06-14
  • 2017-05-23
相关资源
最近更新 更多