use*_*493 42 nserror swift xcode6
var data: NSDictionary =
NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: error) as NSDictionary;
Run Code Online (Sandbox Code Playgroud)
这行代码给了我错误
NSError is not convertable to NSErrorPointer.
Run Code Online (Sandbox Code Playgroud)
所以我想把代码更改为:
var data: NSDictionary =
NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary;
Run Code Online (Sandbox Code Playgroud)
这会将NSError错误转换为NSErrorPointer.但后来我得到一个新的错误,无法理解它:
NSError! is not a subtype of '@|value ST4'
Run Code Online (Sandbox Code Playgroud)
dre*_*wag 69
自Swift 1以来,这些类型和方法发生了很大变化.
NS前缀被丢弃这导致以下代码:
do {
let object = try JSONSerialization.jsonObject(
with: responseData,
options: .allowFragments)
if let dictionary = object as? [String:Any] {
// do something with the dictionary
}
else {
print("Response data is not a dictionary")
}
}
catch {
print("Error parsing response data: \(error)")
}
Run Code Online (Sandbox Code Playgroud)
如果您不关心特定的解析错误:
let object = try JSONSerialization.jsonObject(
with: responseData,
options: .allowFragments)
if let dictionary = object as? [String:Any] {
// do something with the dictionary
}
else {
print("Response data is not a dictionary")
}
Run Code Online (Sandbox Code Playgroud)
原始答案
您的NSError必须定义为,Optional因为它可以是nil:
var error: NSError?
Run Code Online (Sandbox Code Playgroud)
您还想要解释将在返回nil或解析返回数组的解析中出现错误.为此,我们可以使用as?运算符选项.
这给我们留下了完整的代码:
var possibleData = NSJSONSerialization.JSONObjectWithData(
responseData,
options:NSJSONReadingOptions.AllowFragments,
error: &error
) as? NSDictionary;
if let actualError = error {
println("An Error Occurred: \(actualError)")
}
else if let data = possibleData {
// do something with the returned data
}
Run Code Online (Sandbox Code Playgroud)
use*_*195 12
如上所述,错误必须定义为可选(https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/AdoptingCocoaDesignPatterns.html)
但是 - 如果出现错误并返回nil,此代码将崩溃,"As NSDictionary"将成为罪魁祸首:
var data: NSDictionary =
NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary;
Run Code Online (Sandbox Code Playgroud)
你需要像这样进行json解析:
var jsonError : NSError?
let jsonResult : AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &jsonError)
if let error = jsonError{
println("error occurred: \(error.localizedDescription)")
}
else if let jsonDict = jsonResult as? NSDictionary{
println("json is dictionary \(jsonDict)")
}
else if let jsonArray = jsonResult as? NSArray{
println("json is an array: \(jsonArray)")
}
Run Code Online (Sandbox Code Playgroud)
那可行.还记得json可以作为一个数组返回.您没有为选项传递nil,而是可以传递任何您喜欢的内容,例如:
NSJSONReadingOptions.AllowFragments
Run Code Online (Sandbox Code Playgroud)
如果你喜欢.
| 归档时间: |
|
| 查看次数: |
32775 次 |
| 最近记录: |