从Swift xcode 6中的JSON中获取价值

时间:2015-08-07 08:28:45

标签: json swift xcode6 nsurlsession

我有一个JSON文件,我转换为NSDictionary对象。我的问题是如何从这个对象中获取一个单值?我在我的网站上创建了一个httppost,然后我得到一个JSON数组,返回值为“success”,“userId”和“token我想检查”token“中的”access_token“字符串

public class HttpPost{

var URLstring : String = "http://95.85.53.176/nhi/api/app/login"
var ClientSecret : String = "SqzssXGU0C5ukzgvivVTeg7QdlZcnBUKULECgkFp"

public func HttpPostToLogin(Email: String, Password: String, completionHandler: (responseSuccess: Int32) -> ())
{

    var postString = "email=" + Email + "&password=" + Password + "&client_secret=" + ClientSecret

    //Declare URL
    var url: NSURL! = NSURL(string: URLstring)
    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    //Declare which HTTPMethod
    request.HTTPMethod = "POST"

    //POST data
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    //new thread for receiving data
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in

        if error != nil
        {
            println("error=\(error)")
            return
        }

        //Check if there is response from server
        println("response =\(response)")

        var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)


        println("responseString =\(responseString)")


        var error: NSError?

        //parse JSON file
        var myJSON : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &error) as! NSDictionary

        println(myJSON)

        //this works
        var success = myJSON["success"]!.intValue

        //Tried - gives me an error
        //var accessToken = myJSON["token"]["access_token"]!.stringValue

        //println(accessToken)

        //complete task and return success value
        completionHandler(responseSuccess: success!)



    }


    task.resume()

}
}

输出:

{
success = 1;
token =     {
    "access_token" = p9f9ge3Fe1dn5T7xpfBZHfZaA7CwYe9fbLNgeqOY;
    "expires_in" = 604800;
    "refresh_token" = w0qltq4SDax5KtIKEEFZm76CsB9BfozsuSrGuRcI;
    "token_type" = Bearer;
};
userId = 61;
}

2 个答案:

答案 0 :(得分:1)

尝试将值转换为String

var tokenDict: NSDictionary = myJSON["token"] as! NSDictionary
var accessToken: String = tokenDict["access_token"] as! String

对于UserID:

var myUserID: Int = myJSON["userId"] as! Int

答案 1 :(得分:1)

在访问其值之前,您应该检查令牌是否为零。否则app会崩溃。以下代码将在token不为nil且myJSON [“token”]为NSDictionary类型时执行。

if let tokenDict = myJSON["token"] as? NSDictionary {
    var accessToken : String? = tokenDict["access_token"] as? String
    var expires_in  : Int? = tokenDict["expires_in"] as? Int
}