Ordered Dictionary in JSON

前端 未结 4 1708
梦毁少年i
梦毁少年i 2020-12-21 16:28

There are 3 string variables

public var userLoginId : String?
public var searchString : String?
public var tableName : String?

I have a dic

相关标签:
4条回答
  • 2020-12-21 16:40

    Dictionaries are "unordered collections". They do not have any order at all to their key/value pairs. Period.

    If you want an ordered collection, use something other than a dictionary. (an array of single-item dictionaries is one way to do it.) You can also write code that loads a dictionary's keys into a mutable array, sorts the array, then uses the sorted array of keys to fetch key/value pairs in the desired order.

    You could also create your own collection type that uses strings as indexes and keeps the items in sorted order. Swift makes that straightforward, although it would be computationally expensive.

    0 讨论(0)
  • 2020-12-21 16:44

    Dictionaries are unordered

    But !

    Since JSON is a String you can have a sorted JSON. From iOS 11 and macOS 10.13 there is a new option for JSONSerialization for sorting keys that you can use:

    JSONSerialization.data(withJSONObject: json, options: [.sortedKeys])
    
    0 讨论(0)
  • 2020-12-21 16:45

    Not only does Swift's Dictionary not have ordering, but neither do JSON dictionaries, as per the standard. The best you could probably do is store the keys, in correct order, in an array. Instead of iterating the dictionary, you instead iterate the ordered array of keys, and then fetch from the dictionary with those keys.

    To avoid repeating the keys manually, you can express your dictionary as an array of (Key, Value) tuples, like so:

    let keyValuePairs = [
        ("userLoginId", userLoginId),
        ("searchString", searchString),
        ("tableName", tableName)
    ]
    
    
    let dict = Dictionary(uniqueKeysWithValues: keyValuePairs)
    let orderedKeys = keyValuePairs.map { $0.0 }
    

    Now you can use the orderedKeys in your Swift code, or store them in JSON alongside the dict:

    print("Example usage:")
    for key in orderedKeys {
        let value = dict[key]!
        
        print("\(key): \(value)")
    }
    
    0 讨论(0)
  • 2020-12-21 16:51

    I know this was asked a year ago. But I recently ran into this issue while writing unit tests. Basically I wrote up a mock JSON dictionary, used JSONSerialization to turn that into data, and passed that into a parsing object of sorts. In this particular test, however, the order had to be maintained or the test would fail, and the previously described method didn't do that. So what worked for me is instead of starting with a dictionary, I start with a test JSON string and encode that into data using utf8. When it's parsed into a dictionary, the order of the JSON string is maintained in parsed dictionary.

    0 讨论(0)
提交回复
热议问题