简体   繁体   English

使用 Codable 协议以与从服务器接收到的顺序相同的顺序解码 json

[英]Decode the json in same order as received from the server using Codable protocol

So I am parsing my JSON into an object using codable protocol.所以我正在使用可编码协议将我的 JSON 解析为一个对象。 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.我现在面临的是接收 json 的顺序与在对象中解码后的顺序不同。 ie key ordering is not as per json.即键顺序不是按照 json。

I know that it's not a Swift limitation.我知道这不是 Swift 的限制。 Both Swift and JSON Dictionaries are unordered. Swift 和 JSON 字典都是无序的。 The JSON format does not guarantee key ordering, and as such, does not require parsers to preserve the order JSON 格式不保证键顺序,因此不需要解析器保留顺序

But is there any way I can maintain the order??但是有什么办法可以维持秩序??

Dictionary is unordered collection in swift. Dictionary是 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.如果您需要与 json 中相同的顺序,您应该像String一样解析它,然后使用标准String函数以正确的顺序获取数据并将其添加到数组中。 But without Codable :(但是没有Codable :(

Add MutableOrderedDictionary class in your code:在您的代码中添加MutableOrderedDictionary类:

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:您需要将字典传递给sortDictionaryKey函数:

let sortedDict = self.sortDictionaryKey(dictData: YourDictionary)

This code will sort your dictionary into alphabetical order.此代码会将您的字典按字母顺序排序。

Hope this works for you.希望这对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM