问题是当数据不完整时NSJSONSerialization.JSONObjectWithData
使应用程序崩溃而导致unexpectedly found nil while unwrapping an Optional value
错误,而不是通知我们使用NSError变量。所以我们无法阻止崩溃。
您可以在下面找到我们正在使用的代码
var error:NSError? = nil
let dataToUse = NSJSONSerialization.JSONObjectWithData(receivedData, options: NSJSONReadingOptions.AllowFragments, error:&error) as NSDictionary
if error != nil { println( "There was an error in NSJSONSerialization") }
直到现在我们无法找到解决方法。
答案 0 :(得分:45)
针对Swift 3进行了更新
let JSONData = NSData()
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(JSONData, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSONDictionary! \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
}
Swift 2
ffmpeg -i input.mp4 -vf scale=-1:240 -acodec mp3 -vcodec libx264 output.mp4
答案 1 :(得分:24)
问题是您在之前转换了JSON反序列化的结果 检查错误。如果JSON数据无效(例如不完整),那么
NSJSONSerialization.JSONObjectWithData(...)
返回nil
和
NSJSONSerialization.JSONObjectWithData(...) as NSDictionary
会崩溃。
这是一个正确检查错误条件的版本:
var error:NSError? = nil
if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(receivedData, options: nil, error:&error) {
if let dict = jsonObject as? NSDictionary {
println(dict)
} else {
println("not a dictionary")
}
} else {
println("Could not parse JSON: \(error!)")
}
说明:
JSON阅读选项.AllowFragments
在这里没有帮助。设置此选项
只允许那些不是NSArray
或NSDictionary
实例的顶级对象,例如
{ "someString" }
您也可以使用可选演员 as?
在一行中执行此操作:
if let dict = NSJSONSerialization.JSONObjectWithData(receivedData, options: nil, error:nil) as? NSDictionary {
println(dict)
} else {
println("Could not read JSON dictionary")
}
缺点是在else
情况下你无法区分是否阅读
JSON数据失败或者JSON不代表字典。
有关Swift 3的更新,请参阅LightningStryk's answer。
答案 2 :(得分:1)
斯威夫特3:
let jsonData = Data()
do {
guard let parsedResult = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? NSDictionary else {
return
}
print("Parsed Result: \(parsedResult)")
} catch {
print("Error: \(error.localizedDescription)")
}
答案 3 :(得分:0)
这是一个Swift 2扩展,您可以使用它来反序列化NSDictionary:
extension NSJSONSerialization{
public class func dictionaryWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> NSDictionary{
guard let d: NSDictionary = try self.JSONObjectWithData(data, options:opt) as? NSDictionary else{
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotParseResponse, userInfo: [NSLocalizedDescriptionKey : "not a dictionary"])
}
return d;
}
}
对不起,我不确定如何做一个警卫回来,以避免创建临时的'。
答案 4 :(得分:0)
Swift 3 NSJSONSerialization示例(从文件中读取json):
file data.json(例如:http://json.org/example.html)
{
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID":"SGML",
"SortAs":"SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso":[
"GML",
"XML"
]
},
"GlossSee":"markup"
}
}
}
}
}
文件JSONSerialization.swift
extension JSONSerialization {
enum Errors: Error {
case NotDictionary
case NotJSONFormat
}
public class func dictionary(data: Data, options opt: JSONSerialization.ReadingOptions) throws -> NSDictionary {
do {
let JSON = try JSONSerialization.jsonObject(with: data , options:opt)
if let JSONDictionary = JSON as? NSDictionary {
return JSONDictionary
}
throw Errors.NotDictionary
}
catch {
throw Errors.NotJSONFormat
}
}
}
func readJsonFromFile() {
if let path = Bundle.main.path(forResource: "data", ofType: "json") {
if let data = NSData(contentsOfFile: path) as? Data {
do {
let dict = try JSONSerialization.dictionary(data: data, options: .allowFragments)
print(dict)
} catch let error {
print("\(error)")
}
}
}
}