OrderedDictionary encode issue

Hi all,

Here I want to encode OrderedDictionary to JSON file,

I use the JSONEncoder below:

let encoder = JSONEncoder()
        encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]

and I declare variables qwe, asd and zxc:

var qwe = OrderedDictionary<String, Int>()

qwe["bbb"] = 12

qwe["ccc"] = 13

qwe["ddd"] = 14

qwe["bbc"] = 15

var asd = Dictionary<String, Int>()
        
asd["bbb"] = 1
       
asd["ccc"] = 3
       
asd["ddd"] = 4
        
asd["bbc"] = 5
        
var zxc: KeyValuePairs<String, String> {
        
return [
               
 "zz": "zz",
                
"aa": "aa",
                
"bb": "bb",
                
"cc": "cc",
                
"bc": "bc",              
            
]
        
}

After I do try encoder.encode(qwe).write(to: path ,options: .atomic)

encoder.encode(asd).write(to: path ,options: .atomic)

encoder.encode(zxc).write(to: path ,options: .atomic)

the output JSON file format of OrderedDictionary isn't what I expected.

The output JSON of OrderDictionary is like this:

[ "bbb", 12, "ccc", 13, "ddd", 14, "bbc", 15 ]

On the other hand, the output JSON of Dictionary and KeyValuePairs are normal, just with different order:

Dictonary: { "ccc" : 3, "bbb" : 1, "bbc" : 5, "ddd" : 4 }

KeyValuePairs: { "cc" : "cc", "aa" : "aa", "zz" : "zz", "bb" : "bb", "bc" : "bc" }

I also Log these objects after I declare them, the Log show their structure are similar:

qwe -> ["bbb": 12, "ccc": 13, "ddd": 14, "bbc": 15]

asd -> ["ccc": 3, "bbb": 1, "bbc": 5, "ddd": 4]

zxc -> ["zz": "zz", "aa": A"aa", "bb": "bb", "cc": "cc", "bc": "bc"]

I thought the OrderedDictionary is similar to Dictionary, but does anyone know why the output of OrderedDictionary is not like this:

{"bbb": 12, "ccc": 13, "ddd": 14, "bbc": 15}

Or is there any other way I can customize the order of keys in my encoded JSON file?

Thank you so much!

Replies

I don't understand your post.

You say:

does anyone know why the output of OrderedDictionary is not like this: {"bbb": 12, "ccc": 13, "ddd": 14, "bbc": 15}

But just before you wrote:

The output JSON of OrderDictionary is like this: [ "bbb", 12, "ccc", 13, "ddd", 14, "bbc", 15 ]

What is the point ? To have an array and not a dictionary ?

See discussion here: https://forums.swift.org/t/ordereddictionary-decoding/66829