我正在尝试解析来自服务器api的JSON数据。json:
[
{"interest": {
"title":"Sport",
"sub":[
"painting",
"photography",
"museum"]
}
},
{"interest": {
"title": "music",
"sub": [
"rock",
"classic",
"techno"]
}
}]从一个文件中获取它的代码只是为了测试来解析它:
do{
let path = NSBundle.mainBundle().pathForResource("MainInterest", ofType: "json")
let jsonData = NSData(contentsOfFile: path!)
let jsonResult:NSArray! = try NSJSONSerialization.JSONObjectWithData(jsonData! , options: NSJSONReadingOptions.MutableContainers) as! NSArray
} catch let error as NSError {
print(error)
}我可以通过以下方式访问整个文件:
print(jsonResult)但是我不能访问一个以上的级别,这里是第一个级别:
if let a = jsonResult {
print(a[0]["interest"])
}然后我可以从我的文件中获取我的第一个对象,但是我想访问 jsonResult"title"或jsonResult"sub“(==摄影),但是我的这种错误构建失败了:
Cannot subscript a value of type 'AnyObject?!' with an index of type 'String'
Cannot subscript a value of type 'AnyObject?!' with an index of type 'Int'你能帮帮我吗?我真的被困住了,我想苹果医生在这一点上不太清楚。我不想使用像swiftyJson这样的框架。
非常感谢!本
编辑:
解决(谢谢@maxpovver):
//To Get Title
let title = (((self.interests as NSArray)[0] as? NSDictionary)?["interest"] as? NSDictionary)?["title"] as? NSString
print(title)
//To Get Sub
let sub = ((((self.interests as NSArray)[0] as? NSDictionary)?["interest"] as? NSDictionary)?["sub"] as! NSArray)[1] as! NSString发布于 2015-07-23 17:31:16
答案
//To Get Title
let title = (((self.interests as Array)[0] as? Dictionary)?["interest"] as? Dictionary)?["title"] as? String
print(title)
//To Get Sub
let sub = ((((self.interests as Array)[0] as? Dictionary)?["interest"] as? Dictionary)?["sub"] as! Array)[1] as! String还可以使其更具可读性:
let firstInterest = ((self.interests as Array)[0] as? Dictionary)?["interest"] as? Dictionary)?
let title = firstInterest?["title"] as? String
let sub = (firstInterest?["sub"] as! Array)[1] as! String如果没有额外的库,您就永远不可能简化这个问题,因为斯威夫特不支持动态类型。
https://stackoverflow.com/questions/31593594
复制相似问题