![](/img/trans.png)
[英]SWIFT - JSON Error NSCocoaErrorDomain Code=3840 "Garbage at end."
[英]Parsing JSON in Swift 3 after JSON file download, NSCocoaErrorDomain Code=3840
因此,當我嘗試為要構建的應用程序下載的JSON對象執行JSONSerialization時,始終出現以下錯誤。 基本上,我要做的是創建一個JSON文件,將其保存在SugarSync上,並獲得直接下載鏈接以在程序中下載和使用。 有點我自己的bootleg API。
我知道它會下載,因為如果我使用URL將文件轉換為字符串,它會打印出文件。 問題是我無法克服此錯誤。
錯誤域= NSCocoaErrorDomain代碼= 3840“字符2周圍的對象中的值沒有字符串鍵。”
這是文件讀取方式的一個示例(超級簡單!):
{"buddy": "pal",
"brother": "bear"}
我嘗試更改為NSData而不是Data,但這會帶來更多問題。 嘗試在JSONSerialization行上執行NSDictionary,但這會引發更多錯誤。 我也嘗試了.mutableContainers,也無濟於事。
下面是完整的代碼,包括SugarSync文件URL,以便您自己重新創建錯誤。 我不明白自己在做什么錯,如果有人可以提供幫助,那就太了不起了。
謝謝!
// Create destination URL
let documentsURL: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsURL.appendingPathComponent("downloadedFile.json")
// Create URL to the source file you want to download
let fileURL = URL(string: "https://www.sugarsync.com/pf/D7126167_796_275761334?directDownload=true")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url: fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
print("move files")
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
let fileData: Data = try Data(contentsOf: destinationFileUrl, options: Data.ReadingOptions.mappedIfSafe)
print(fileData)
let myJson = try JSONSerialization.jsonObject(with: fileData, options: []) as? [[String: Any]]
print(myJson!)
do {
// This converts the file into String and is printed (doesn't get to this because of the error, but it works!)
let jsonText = try String(contentsOf: tempLocalUrl, encoding: String.Encoding.utf8)
print(jsonText)
} catch {
print("failed to print json file")
}
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading file. Error description: %@", error?.localizedDescription ?? "unknown")
}
}
task.resume()
編輯---------------------------看來序列化非常敏感。 它需要這樣的東西才能工作:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
但這是行不通的:
{“website”: {
“iPhone”: {
“blogURL”: ”string”,
“blogHead”: “string”,
“reportURL”: “string”,
“reportHead”: “string”
}
}}
注意:此網站未正確顯示JSON縮進。 這是我獲取JSON示例的地方 。
您正在嘗試解析類型[[String: Any]]
的JSON,而該JSON僅僅是字典( [String: Any]
)而不是字典數組。
嘗試更改為此:
let myJson = try JSONSerialization.jsonObject(with: fileData, options: []) as? [String: Any]
最終解決了。 事實證明,正如我在編輯中所述,json序列化程序非常敏感。 因此,我決定使用此JSON在線編輯器來確保我需要的所有內容都是絕對正確的,包括正確的字體和大小等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.