las*_*sej 9 json swift codable
是否可以将 Swift JSON 编码器配置为使用结构体属性的排序顺序作为 JSON 输出中字典键的排序顺序?默认情况下,它使用一些任意(但看似不是随机)的顺序,例如......
struct Example: Codable {
let id: Int
let name: String
let createdAt: Date
let comments: [String]
}
Run Code Online (Sandbox Code Playgroud)
... 结果是 ...
"example" : {
"id" : 1,
"name" : "Test",
"comments" : [
"Comment 1",
"Comment 2"
],
"createdAt" : 549539643.25327206
}
Run Code Online (Sandbox Code Playgroud)
我知道从语义上来说顺序并不重要,但我想保留它以用于调试目的。
JSONEncoder有财产outputFormatting,你可以这样做,
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
Run Code Online (Sandbox Code Playgroud)
我没有尝试过,请尝试告诉我。