简体   繁体   English

SwiftyJson和Alamofire

[英]SwiftyJson and Alamofire

I am trying to combine Alamofire and SwiftJSON, but every tutorial I have followed does not work. 我正在尝试将Alamofire和SwiftJSON结合起来,但是我遵循的每个教程都不起作用。 Here is my code: 这是我的代码:

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")
                }

            }

    }

I just want to get the cell phone number from the json data. 我只想从json数据中获取手机号码。 The JSON returns in the following format: 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"
    }
  }
}
]
}

When I try to print cell it returns nil. 当我尝试打印cell它返回nil。 Any help is appreciated!!! 任何帮助表示赞赏!!!

Try this: 尝试这个:

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")
                }

            }

    }

The problem was that you had ordered the subscripts incorrectly: you need first to access the value of the "results" key, next you need the first item in the array, and so on. 问题是您下标的顺序不正确:首先需要访问“结果”键的值,其次需要数组中的第一项,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM