我有一个通过http与服务器通信的快速应用程序,
我通过这个服务器得到的答案可能是json,也可能不是。我需要检查他们将答案打印为DictionaryArray,以避免fatal error: unexpectedly found nil while unwrapping an Optional value处的NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
这是我的jsonObjectWithData

var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error:nil)!
elimResponse = response?.description
elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

我想得到的是:
if dataVal is Json{
    elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
    println(elimJson)
    }else{
    elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
    println(elim)
    }

谢谢你的帮助。当做。

最佳答案

您可以在if let中尝试以下类型的转换:

if let elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: nil, error: nil) as? NSDictionary {
    println("elim is a dictionary")
    println(elim)
} else if let elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: nil, error: nil) as? NSArray {
    println("elim is an array")
    println(elim)
} else {
    println("dataVal is not valid JSON data")
}

SWIFT 2.0的更新
do {
    if let elim = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
        print("elim is a dictionary")
        print(elim)
    } else if let elim = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSArray {
        print("elim is an array")
        print(elim)
    } else {
        print("dataVal is not valid JSON data")
    }
} catch let error as NSError {
    print(error)
}

10-06 10:29