首页 > 解决方案 > 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 类型来按字母顺序对键进行排序。但我不明白是否以及如何利用此属性对嵌套的可编码对象进行排序。

有谁知道如何对我需要的编码消息进行排序?

标签: jsonswiftencoding

解决方案


推荐阅读