无法将已排序的字典序列化为 JSON - Swift 3
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)
}
}
有趣的是,在检查器中调试未排序的字典时看起来像这样:unsorted dictionary and sorted looks like this sorted dictionary
请帮忙解决这个问题。
首先,在 Swift stdlib 中没有排序的目录(或者在 JSON 中;JSON 对象是无序的)。当你在字典上调用 .sorted()
时,它 returns 一个 key/value 对 [(Key, Value)]
.
的数组
JSONSerialization
有关于它可以序列化的内容的规则:
顶级对象是 NSArray 或 NSDictionary。
所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
所有字典键都是 NSString 的实例。
数字不是 NaN 或无穷大。
存在从 NS 兼容集合到它们的 NS 等价物的隐式桥梁,但只有当内容可以用 ObjC 表达时才能得到这个((Key, Value)
不能)。
如何正确实现这一点在很大程度上取决于 tempDictionaryForJsonFile
的类型和内容,此处未给出。它还取决于您尝试使用 "sorted dictionary" 实现的目标(JSON 中不存在,因此无法从 Swift 获取它)。如果你的意思是 "an ordered array of JSON objects, each with one key/value," 可以构建(但你需要在任何消耗此数据的情况下支持它)。
无法通过 JSONSerialization.data(withJSONObject:options:)
序列化适用于未排序的字典,但对于已排序的应用程序会抛出描述错误:
*** 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)
}
}
有趣的是,在检查器中调试未排序的字典时看起来像这样:unsorted dictionary and sorted looks like this sorted dictionary
请帮忙解决这个问题。
首先,在 Swift stdlib 中没有排序的目录(或者在 JSON 中;JSON 对象是无序的)。当你在字典上调用 .sorted()
时,它 returns 一个 key/value 对 [(Key, Value)]
.
JSONSerialization
有关于它可以序列化的内容的规则:
顶级对象是 NSArray 或 NSDictionary。
所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
所有字典键都是 NSString 的实例。
数字不是 NaN 或无穷大。
存在从 NS 兼容集合到它们的 NS 等价物的隐式桥梁,但只有当内容可以用 ObjC 表达时才能得到这个((Key, Value)
不能)。
如何正确实现这一点在很大程度上取决于 tempDictionaryForJsonFile
的类型和内容,此处未给出。它还取决于您尝试使用 "sorted dictionary" 实现的目标(JSON 中不存在,因此无法从 Swift 获取它)。如果你的意思是 "an ordered array of JSON objects, each with one key/value," 可以构建(但你需要在任何消耗此数据的情况下支持它)。