我一直在使用以下代码行来解析Objective-C中的JSON数据,但Swift中的相同内容会使应用程序崩溃。
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:_webData
options:kNilOptions
error:&error];
我尝试使用NSJSONReadingOptions.MutableContainers
,但似乎无法正常工作。我已经使用在线发现的各种JSON有效性检查器验证了从Web服务器获取的JSON数据的有效性。
[编辑]我使用的快捷代码如下:
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
[UPDATE]
使用let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
解决了这个问题。
答案 0 :(得分:3)
错误Xcode给你的帮助并不大,但看起来你需要以不同的方式声明你的error
变量(more at Apple's documentation),然后确保你处理字典回归nil
:
var error: AutoreleasingUnsafePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data,
options:NSJSONReadingOptions.MutableContainers,
error: error) as? NSDictionary
if jsonResult {
// process jsonResult
} else {
// couldn't load JSON, look at error
}
答案 1 :(得分:3)
所有答案对我都没有用。这工作(2015年1月21日 - Xcode 6.1.1 / iOS 8.1.2):
var err: AutoreleasingUnsafeMutablePointer<NSError?> = nil
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:err) as NSDictionary
在此处找到:Use of undeclared type AutoreleasingUnsafePointer Xcode 6 beta 6
答案 2 :(得分:1)
Nil必须工作,我认为您的错误来自另一个问题,请发布更多代码/崩溃日志
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
你能试试吗?
答案 3 :(得分:0)
// Created a NSDictionary to hold the data
var tempLocations : NSArray = NSArray()
var modelLocation : [Location] = [] // Will hold all the locations read in from datafile
// setup the path for the data
let jsonData = NSData(contentsOfURL: fullPathForDataFile)
if let realJsonData = jsonData { // doing a test to check that the data exists
tempLocations = NSJSONSerialization.JSONObjectWithData(realJsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSArray
println("imported location data file with \(error) errors")
} else {
// The data file does not exist, tell the user!
}
// For each set of object data in the json file do a loop.
for room in 1..<tempLocations.count {
var newlocation : Location // This object contains var code:String?
newlocation.code = tempLocations[room].valueForKey("code") as String
// save the new location somewhere.
modelLocation.addObject(newLocation)
}