Is it possible to configure the Swift JSON encoder to use the sort order of the struct properties as the sort order of the dictionary keys in the JSON output? By default it uses some arbitrary (but seemingly not random) order, e.g. ...
struct Example: Codable {
let id: Int
let name: String
let createdAt: Date
let comments: [String]
}
... results in ...
"example" : {
"id" : 1,
"name" : "Test",
"comments" : [
"Comment 1",
"Comment 2"
],
"createdAt" : 549539643.25327206
}
I know that semantically the order doesn't matter, but I'd like to keep it for debugging purposes.
JSONEncoder has outputFormatting property, you can do this,
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
I've not tried it, please try and let me know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With