LeTadas
LeTadas

Reputation: 3556

Swift keep order while converting to JSON using JSONEncoder

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)}
     """
 }

Upvotes: 6

Views: 2204

Answers (1)

Fattie
Fattie

Reputation: 12272

I'm just putting in an answer since nobody has.

This is a completely common and normal problem. Any number of data stores on the cloud, while fetching say an image, take a long pile of json as a url argument.

This is messy and pathetic but then, as programming companies, we do not get to take over the cloud side in 100% of cases :)

This causes all sorts of nuisance when you are dealing with image caches and such.

As was mentioned in comments

  1. Just use outputFormatting = .sortedKeys and then it will always be the same which in some cases solves the problem at hand

  2. Just arrange to prepend AAAA1_, AAAA2_ and so on to the names (in the order you desire), then use .sortedKeys, then strip those out with a regex.

  3. Unfortunately yes, Apple does not currently offer a solution, so you'd have to write your own, which is never a good idea.

Upvotes: 1

Related Questions