はJSONSerialization.data(withJSONObject:options:)
はJSONにソートされた辞書をシリアライズすることはできませんスウィフト3
シリアライズがソートされていない辞書で動作しますが、ソートされたアプリで記述してエラーをスローを経由してJSONに私のソートされた辞書をシリアライズすることはできません
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
この問題の解決にお役立てください。
「辞書」には順序がありません。 –