gpt4 book ai didi

ios - 无法将排序的字典序列化为 JSON - Swift 3

转载 作者:行者123 更新时间:2023-11-28 15:56:56 27 4
gpt4 key购买 nike

无法通过 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排序看起来像这样sorted dictionary

请帮助解决这个问题。

最佳答案

首先,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 对象数组,每个对象都有一个键/值”,那么可以构建它(但是您需要在使用此数据的任何地方支持它)。

关于ios - 无法将排序的字典序列化为 JSON - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41595522/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com