Swift keep order while converting to JSON using JSONEncoder

Viewed 556

How can I convert Codable struct to a JSON Data object and keep the order of the struct variables? I know that Dictionary is not ordered and that JSONEncoder and JSONSerialization.data accepts only Dictionary or Array. I need it to contain order only for URLRequest httpBody, but not when receiving data. As httpBody is Data object maybe I can avoid using JSONEncoder and convert struct straight to a Data object?

struct RequestBody: Codable {
    let paramB: String
    let paramC: String
    let paramA: String
}

Currently, the only way I figured out to do it is manually convert it to JSON string:

func toString() -> String {
  return """
        {"paramB":paramB,"paramC":\(paramC),"paramA":\(paramA)}
     """
 }
0 Answers
Related