如果尝试获取字符串对象
,则(Xcode6 BETA 6)出错let jsonString : String = "[{\"name\":[\"Fred\",\"John\"],\"age\":21},{\"name\":\"Bob\",\"age\":35}]"
let myData:NSData? = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var jsonResult:NSArray = NSJSONSerialization.JSONObjectWithData(myData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray
println(jsonResult.objectAtIndex(0).objectForKey("name").objectAtIndex(0))
打印永远不会被调用,导致错误。有人有想法吗?
答案 0 :(得分:10)
从NSDictionary或NSArray获取值返回AnyObject对象。所以你应该输入适当的类型。试试这个
println(((jsonResult.objectAtIndex(0) as NSDictionary).objectForKey("name") as NSArray).objectAtIndex(0))
答案 1 :(得分:1)
我建议创建一个或多个类并反序列化该JSON,以便更好地访问数据并避免访问时出错。
顺便说一下,通过使数据类型更加明确,它可以工作:
let dict = jsonResult.objectAtIndex(0) as NSDictionary
let array = dict["name"] as NSArray
println(array.objectAtIndex(0))
答案 2 :(得分:1)
另一种选择是将jsonResult
投射到Array<AnyObject>
并使用subscript
语法来获取必要的值
let jsonString : String = "[{\"name\":[\"Fred\",\"John\"],\"age\":21},{\"name\":\"Bob\",\"age\":35}]"
let myData:NSData? = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var jsonResult: AnyObject = NSJSONSerialization.JSONObjectWithData(myData!, options: NSJSONReadingOptions.MutableContainers, error: nil);
if let lJsonArray = jsonResult as? Array<AnyObject> {
println(lJsonArray[0].objectForKey("name")[0])
}