Got a error on (Xcode6 BETA 6) if a try to get an object of string:
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))
print never get called, cause the error. Anyone a idea?
Getting value from NSDictionary or NSArray return AnyObject object. So you should type cast to appropriate type. Try this
println(((jsonResult.objectAtIndex(0) as NSDictionary).objectForKey("name") as NSArray).objectAtIndex(0))
Another option would be to cast jsonResult
to an Array<AnyObject>
and use subscript
syntax to get necessary value
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])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With