Home > Software engineering >  How to make json keys as a special order in Swift JSONEncoder?
How to make json keys as a special order in Swift JSONEncoder?

Time:10-24

I need make a request to a server of an open API. The rule of the open API asked json parameter must make keys as a special order(not the A-Z order nor Z-A order).

struct Req : Encodable {
    let SourceText: String
    let Target: String
    let Source: String
    let ProjectId: Int = 0
}

What I want is:

{"SourceText":"你好","Source":"zh","Target":"en","ProjectId":0}

But the encoded json is:

{"ProjectId":0,"Source":"zh","SourceText":"你好","Target":"en"}

CodePudding user response:

With JSONEncoder i think that isn't possible.

One possible workaround is to use key placeholders, e.g. keyA, keyB, keyC, let them sort them alphabetically and then just replace them using a dictionary in the resulting JSON from this question I hope is helpful.

However, JSON is:

"An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array."

RFC 7159

CodePudding user response:

One workaround here that is ok if you don't have to many properties or custom types is to build a string containing the json and then convert it to Data

extension Req {
    var jsonString: String {
        String(format: #"{""SourceText": "%@, "Source": %@, "Target": %@, "ProjectId": %d}"#,
               SourceText, Source, Target, ProjectId)
    }
}

or directly returning Data?

extension Req {
    var json: Data? {
        String(format: #"{""SourceText": "%@, "Source": %@, "Target": %@, "ProjectId": %d}"#,
               SourceText, Source, Target, ProjectId).data(using: .utf8)
    }
}
  • Related