如何编码包装器类型,以使其无法在容器中嵌套?
通常,如果我有这样的结构:
struct Box: Codable {
let id: String
/// This is an expression (e.g. `x + 3`) rather than a number.
let height: String
}
它将被编码为JSON,如下所示:
{
"id": "box1",
"height": "x + 3"
}
问题是我想引入一个新的包装器类型expression
,以使我显然不应该使用正常该属性中的字符串:
struct Box: Codable {
let id: String
let height: Expression
}
struct Expression: Codable {
let string: String
}
现在使用此包装器类型更清楚API,但是现在嵌套了JSON:
{
"id": "box1",
"height": {
"string": "x + 3"
}
}
我想删除此嵌套,因此看起来再次这样:
{
"id": "box1",
"height": "x + 3"
}
我宁愿不要在上覆盖任何内容box
以来:
- 框可能还有许多其他属性,我宁愿不必手动维护编码/解码功能。
- 使用
表达式
的其他任何地方都应从这种非巢容器行为中受益,而我在不编写更编码的样板的情况下。
因此,我只想修改expression
,并将其输出其编码数据而不引入额外的容器。
我尝试使用container.superencoder()
as 此处提到的,但这保持了相同的层次结构,并重命名为“字符串”
“ super” 。
Normally if I have a struct like this:
struct Box: Codable {
let id: String
/// This is an expression (e.g. `x + 3`) rather than a number.
let height: String
}
It would get encoded as JSON as follows:
{
"id": "box1",
"height": "x + 3"
}
The problem is that I want to introduce a new wrapper type Expression
to make it obvious that I shouldn't be using normal strings in this property:
struct Box: Codable {
let id: String
let height: Expression
}
struct Expression: Codable {
let string: String
}
The API is now more clear with this wrapper type, but the JSON is now nested:
{
"id": "box1",
"height": {
"string": "x + 3"
}
}
I'd like to remove this nesting so it looks like this again:
{
"id": "box1",
"height": "x + 3"
}
I'd prefer not to override anything on Box
since:
- Box may have many other properties and I'd rather not have to maintain the encode/decode functions manually.
- Anywhere else that
Expression
is used should benefit from this non-nested container behavior without me writing more Codable boilerplate.
Therefore, I'd like to only modify Expression
, and get it to output its encoded data without introducing an extra container.
I tried using container.superEncoder()
as mentioned here, but that kept the same hierarchy and renamed "string"
with "super"
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,请注意,代码的标准实现如下:
请注意,它如何添加容器内部器/解码器。
取而代之的是,您要做的是与直接发送的编码器/解码器进行交互:
这将编码/解码对象,好像自定义包装器不存在:
First, notice that the standard implementation of Codable is as follows:
Notice how it adds a container insider the encoder/decoder.
Instead, what you want to do is interact with the encoder/decoder that is sent directly:
This will encode/decode the object as though the custom wrapper doesn't exist: