iflet statusesArray =JSONObjectas? [AnyObject], let status = statusesArray[0] as? [String: AnyObject], let user = status["user"] as? [String: AnyObject], let username = user["name"] as?String { // Finally we got the username }
很不优雅……
但是用了SwiftJSON之后这样就可以得到了
1 2 3 4 5 6
let json =JSON(data: dataFromNetworking) iflet userName = json[0]["user"]["name"].string{ //Now you got your value }
而且随便玩,完全不用担心程序崩溃。如果数组访问越界或者数据不存在它自动返回nil
1 2 3 4 5 6 7 8 9
let json =JSON(data: dataFromNetworking) iflet userName = json[999999]["wrong_key"]["wrong_name"].string{ //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety } else { //Print the error println(json[999999]["wrong_key"]["wrong_name"]) }