首页 > 解决方案 > 将类编码为单个值而不是字典 swift

问题描述

给定课程:

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 吗?

标签: swiftencodable

解决方案


您可以通过自定义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 对象。而且您不必接触外部类。


推荐阅读