1

So I am parsing my JSON into an object using codable protocol. What I am facing right now is that the order in which json is received is not the same as in which after decoding it in an object. ie key ordering is not as per json.

I know that it's not a Swift limitation. Both Swift and JSON Dictionaries are unordered. The JSON format does not guarantee key ordering, and as such, does not require parsers to preserve the order

But is there any way I can maintain the order ??

arinjay
  • 83
  • 7
  • 1
    If the order is important, it should be an array. Otherwise you will have a problem with such a JSON in most languages. – Sulthan Nov 16 '19 at 14:39
  • Maybe [this](https://stackoverflow.com/questions/33996986/swift-a-sorted-dictionary) could be of help or [this](https://stackoverflow.com/a/51092314/9223839) – Joakim Danielson Nov 16 '19 at 14:41

2 Answers2

1

Dictionary is unordered collection in swift. If you need the same order as in json, you should parse it like String and then get data with correct order using standard String functions and add it to an array. But without Codable :(

I. Pedan
  • 244
  • 2
  • 9
-1

Add MutableOrderedDictionary class in your code:

class MutableOrderedDictionary: NSDictionary {

    let _values: NSMutableArray = []
    let _keys: NSMutableOrderedSet = []

    override var count: Int {
        return _keys.count
    }
    override func keyEnumerator() -> NSEnumerator {
        return _keys.objectEnumerator()
    }
    override func object(forKey aKey: Any) -> Any? {
        let index = _keys.index(of: aKey)
        if index != NSNotFound {
            return _values[index]
        }
        return nil
    }
    func setObject(_ anObject: Any, forKey aKey: String) {
        let index = _keys.index(of: aKey)
        if index != NSNotFound {
            _values[index] = anObject
        } else {
            _keys.add(aKey)
            _values.add(anObject)
        }
    }
}

Add this function in your code:

//MARK: - Sort Dictionary Key by the Ascending order
    static func sortDictionaryKey(dictData : [String : Any]) -> MutableOrderedDictionary {

        // initializing empty ordered dictionary
        let orderedDic = MutableOrderedDictionary()
        // copying normalDic in orderedDic after a sort
        dictData.sorted { $0.0.compare($1.0) == .orderedAscending }
            .forEach { orderedDic.setObject($0.value, forKey: $0.key) }
        // from now, looping on orderedDic will be done in the alphabetical order of the keys
        orderedDic.forEach { print($0) }

        return orderedDic
    }

You need to pass dictionary to sortDictionaryKey function:

let sortedDict = self.sortDictionaryKey(dictData: YourDictionary)

This code will sort your dictionary into alphabetical order.

Hope this works for you.