Не может сериализовать мой отсортированный словарь в JSON с помощью JSONSerialization.data(withJSONObject:options:)
Не может сериализации отсортированного словаря для JSON - Swift 3
сериализации работает с несортированным словарем, но с отсортированным приложением выбрасывает ошибку с описанием:
*** 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
Помогите решить эту проблему.
'Словарь' не имеет никакого заказа. –