Removing nulls from a JSON structure recursively

后端 未结 4 2004
忘了有多久
忘了有多久 2021-01-05 22:46

I\'m frequently finding the need to cache data structures created by NSJSONSerialization to disk and as -writeToFile fails if there are nulls, I ne

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 23:36

    Swift 4 version of @Travis M.'s answer;

    class func removeNullFromJSONData(_ JSONData: Any) -> Any {
        if JSONData as? NSNull != nil {
            return JSONData
        }
    
        var JSONObject: Any!
    
        if JSONData as? NSData != nil {
            JSONObject = try! JSONSerialization.data(withJSONObject: JSONData, options: JSONSerialization.WritingOptions.prettyPrinted)
        }
        else {
            JSONObject = JSONData
        }
    
        if JSONObject as? NSArray != nil {
            let mutableArray: NSMutableArray = NSMutableArray(array: JSONObject as! [Any], copyItems: true)
            let indexesToRemove: NSMutableIndexSet = NSMutableIndexSet()
    
            for index in 0 ..< mutableArray.count {
                let indexObject: Any = mutableArray[index]
    
                if indexObject as? NSNull != nil {
                    indexesToRemove.add(index)
                }
                else {
                    mutableArray.replaceObject(at: index, with: removeNullFromJSONData(indexObject))
                }
            }
    
            mutableArray.removeObjects(at: indexesToRemove as IndexSet)
    
            return mutableArray;
        }
        else if JSONObject as? NSDictionary != nil {
            let mutableDictionary: NSMutableDictionary = NSMutableDictionary(dictionary: JSONObject as! [AnyHashable : Any], copyItems: true)
    
            for key in mutableDictionary.allKeys {
                let indexObject: Any = mutableDictionary[key] as Any
    
                if indexObject as? NSNull != nil {
                    mutableDictionary.removeObject(forKey: key)
                }
                else {
                    mutableDictionary.setObject(removeNullFromJSONData(indexObject), forKey: key as! NSCopying)
                }
            }
    
            return mutableDictionary
        }
        else {
            return JSONObject
        }
    }
    

提交回复
热议问题