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
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
}
}