[英]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.