SwiftyJson和Alamofire

时间:2015-04-23 12:45:18

标签: ios json swift alamofire swifty-json

我正在尝试将Alamofire和SwiftJSON结合起来,但我所遵循的每个教程都不起作用。这是我的代码:

request(.GET, "http://api.randomuser.me", parameters: nil)
        .responseJSON { (req, res, json, error) in
            if(error != nil) {

            }
            else {
                var json = JSON(json!)
                if let cell = json[0]["results"]["cell"]["registered"].string{
                    //Now you got your value
                    println(cell)
                }
                else
                {
                    println("error")
                }

            }

    }

我只是想从json数据中获取手机号码。 JSON以下列格式返回:

{
"results" : [
{
  "seed" : "85a9f46b169c1d3f",
  "user" : {
    "sha256" : "bd60a88fb92ee4b50c51b2e22acd2196e5b1b0317fbbd97d1c554d2437abc577",
    "cell" : "(699)-992-8562",
    "phone" : "(810)-927-4340",
    "version" : "0.5",
    "SSN" : "140-22-8290",
    "nationality" : "US",
    "sha1" : "23a62834c34efdc8fab5e02c47a96d204f18bad7",
    "registered" : "1289959546",
    "dob" : "101759680",
    "picture" : {
      "large" : "http:\/\/api.randomuser.me\/portraits\/women\/2.jpg",
      "thumbnail" : "http:\/\/api.randomuser.me\/portraits\/thumb\/women\/2.jpg",
      "medium" : "http:\/\/api.randomuser.me\/portraits\/med\/women\/2.jpg"
    },
    "location" : {
      "state" : "mississippi",
      "street" : "8718 marsh ln",
      "city" : "las vegas",
      "zip" : "34685"
    },
    "password" : "molson",
    "salt" : "SFdoIQnc",
    "username" : "silverladybug271",
    "md5" : "8f15f0d67a9e7610312dc8e62c766943",
    "email" : "felecia.andrews12@example.com",
    "gender" : "female",
    "name" : {
      "title" : "mrs",
      "first" : "felecia",
      "last" : "andrews"
    }
  }
}
]
}

当我尝试打印cell时,它返回nil。任何帮助表示赞赏!!!

1 个答案:

答案 0 :(得分:3)

试试这个:

request(.GET, "http://api.randomuser.me", parameters: nil)
        .responseJSON { (req, res, json, error) in
            if(error != nil) {

            }
            else {
                var json = JSON(json!)
                if let cell = json["results"][0]["user"]["cell"].string{
                    //Now you got your value
                    println(cell)
                }
                else
                {
                    println("error")
                }

            }

    }

问题在于您错误地订购了下标:首先需要访问“结果”键的值,接下来需要数组中的第一项,依此类推。