【问题标题】:encode class to single value not dictionary swift将类编码为单个值而不是字典 swift
【发布时间】:2020-01-06 21:56:57
【问题描述】:

给定类:

class ComplementApp: Codable{
    let name: String
    let idSpring: String
}

class MasterClass: Encodable{
    let complement: ComplementApp
    ///Other propierties
}

我想得到:

//Where "Some ID" is the value of complement.idSpring
{
   complement: "Some ID"
   //Plus the other properties
}

没有

{
   complement: {
      name: "Some Name",
      idSpring: "Some ID"
   }
   //Plus other properties
}

这是默认设置。 我知道我可以在 MasterClass 中抛出编码函数和 CodingKeys,但我还有 20 个其他变量,我应该添加 19 个额外的键。我可以在 ComplementApp 中实现这个实现 CodingKeys 吗?

【问题讨论】:

  • 补码以String方式存储所有属性就够了吗?
  • 我的意思是因为例如你可以做一些类似的事情:“Some Name|Some ID”
  • 嗯...不,我在不同的情况下使用这两个属性。

标签: swift encodable


【解决方案1】:

您可以通过自定义encode(to:) 实现来实现这一点:

class ComplementApp: Codable {
    let name: String
    let idSpring: String

    func encode(to coder: Encoder) throws {
        var container = coder.singleValueContainer()
        try container.encode(idSpring)
    }
}

使用 singleValueContainer 将导致您的对象被编码为单个值而不是 JSON 对象。而且你不必接触外部类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2014-01-14
    • 2020-11-05
    • 2016-11-13
    • 2020-04-01
    • 2021-06-12
    相关资源
    最近更新 更多