json - Swift JsonEncoder 元素顺序
问题描述
我目前正在做一个项目,遗憾的是提供的 API 是一团糟。在这篇关于 Indeterminate Types with Codable in Swift 的中篇文章中的第一个解决方案之后,我正在使用多个嵌套类型对 Codable 进行编码。因此,我使用枚举来允许在我的可编码消息中使用不同的类型,大致如下:
struct CommandBase: Encodable {
let command: CommandType
enum CodingKeys: String, CodingKey {
let command = "c"
}
}
enum CommandType: Encodable {
case someCommand(someContainer)
case someOtherCommand(someOtherContainer)
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .someCommand(let someContainer):
try container.encode("something", forkey: .name)
try container.encode(someContainer, forKey: .container)
try container.encode("etc", forKey: .etc)
case .someOtherCommand(let someOtherContainer):
// about the same as above case
}
}
enum CodingKeys: String, CodingKey {
case name
case container
case etc
}
}
问题是,正如我提到的,我必须使用的 API 是一团糟,并且需要以正确的顺序获取 json。但由于某种原因,标准 JsonEncoder 总是将 .container 放在首位。
这是一个重构,早期版本使用了几种泛型类型,导致代码难以阅读,但顺序得到了满足。
JsonEncoder 有一个 outputFormatting 属性,它使用像 .sortedKeys 这样的 OutputFormatting 类型来按字母顺序对键进行排序。但我不明白是否以及如何利用此属性对嵌套的可编码对象进行排序。
有谁知道如何对我需要的编码消息进行排序?
解决方案
推荐阅读
- c# - OpenXML:使用 Element.Val 和 Element{ Val = "Val" } 的区别
- c# - 如何将从 api 传递的对象转换回该项目的类?
- python - 批处理文件以激活 env 并运行 spyder。CMD 保持打开状态
- sql - 如何在 PostgreSQL 中执行 COPY TO 而不重新排序 CSV 文件
- c# - 向 exec 过程添加新参数
- swift - 使用 DispatchGroup 时从未调用过 Swift 完成处理程序
- ubuntu - rsync:如何将 Ubuntu 本地文件传输到 Google Cloud Storage?
- c# - 使用 C# (mongocsharpdriver) 在 MongoDB 中查找不同的计数
- python - 如何使用硒在python中按标签
- sql - 在一行中只查找重复项