swift - 将类编码为单个值而不是字典 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 吗?
解决方案
您可以通过自定义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 对象。而且您不必接触外部类。
推荐阅读
- r - R 错误:`n()` 只能在 dplyr 动词中使用
- java - 如何为我的导出自定义作业修复此错误?
- jwt - JWT Token .NET Core 身份服务器问题
- python - 在 lambda 语句中使用迭代器
- python - 将日期中的总音量拆分为小时数 python pandas
- r - Plotly-R:如何制作有间隙的 y 轴?
- javascript - 我必须从 Vuejs 中的多个输入中创建一个字符串数组。我该怎么办?
- java - 如何为 JPA 连接设置 ReadTimeout
- apache - 如何使用 Keycloak 保护通过 httpd 公开的静态文件?
- kong - 是否可以使用 kong response-transformation 插件替换正文响应中的 json 属性?