Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)}
     """
 }
like image 302
LeTadas Avatar asked Aug 16 '26 04:08

LeTadas


1 Answers

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.

like image 177
Fattie Avatar answered Aug 17 '26 23:08

Fattie