[英]Cannot serializing sorted dictionary to JSON - Swift 3
无法通过JSONSerialization.data(withJSONObject:options:)
排序后的字典序列化为JSON
序列化适用于未排序的字典,但与已排序的应用程序一起引发描述错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
这是我的方法的样子:
func createJSONFile(){
// create path to json file
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = urls[0] as NSURL
guard let jsonURL = documentDirectory.appendingPathComponent("graphData") else {
print("Failed to create path to json file.")
return
}
print(jsonURL.absoluteString)
// creating a .json file in the Documents folder
if !fileManager.fileExists(atPath: jsonURL.absoluteString){
fileManager.createFile(atPath: jsonURL.absoluteString, contents: nil, attributes: nil)
print("file created")
}
do {
let unsortedDic = self.tempDictionaryForJsonFile
let sortedDic = unsortedDic.sorted(by: <)
let jsonData = try JSONSerialization.data(withJSONObject: sortedDic, options: .prettyPrinted)
print(jsonData)
try jsonData.write(to: jsonURL)
print(fileManager.fileExists(atPath: jsonURL.absoluteString))
let content = try String.init(contentsOf: jsonURL, encoding: .utf8)
print(content)
} catch {
print(error.localizedDescription)
}
}
有趣的是,在检查器中调试未排序的字典时看起来像这样: 未排序的字典和已排序的看起来像这个已排序的字典
请帮助解决此问题。
首先,Swift stdlib中没有排序目录(或者在JSON中没有排序目录; JSON对象是无序的)。 当您在字典上调用.sorted()
时,它将返回键/值对[(Key, Value)]
的数组。
JSONSerialization
有关于可以序列化的规则:
顶级对象是NSArray或NSDictionary。
所有对象都是NSString,NSNumber,NSArray,NSDictionary或NSNull的实例。
所有字典键都是NSString的实例。
数字不是NaN或无穷大。
从与NS兼容的集合到与它们等效的NS之间存在隐式桥梁,但只有在内容可以用ObjC表示(而(Key, Value)
不能表示)的情况下,您才能获得此桥。
如何正确实现此方法在很大程度上取决于tempDictionaryForJsonFile
的类型和内容(此处未提供)。 它还取决于您要使用“排序字典”(JSON中不存在,因此无法从Swift进行获取)来实现的目的。 如果您的意思是“可以构建一个有序的JSON对象数组,每个对象都有一个键/值”(但是无论使用哪种数据,都需要对其进行支持)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.