从 JSON in Swift xcode 中获取价值 6
Get value out from JSON in Swift xcode 6
我有一个 JSON 文件,我将其转换为 NSDictionary 对象。我的问题是如何从该对象中获取一个值?我在我的网站上做了一个 httppost,然后我得到一个 JSON 数组返回值 "success" ,"userId" 和 "token i want to check on the "access_token" string in "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;
}
尝试将值转换为 String
var tokenDict: NSDictionary = myJSON["token"] as! NSDictionary
var accessToken: String = tokenDict["access_token"] as! String
对于用户 ID:
var myUserID: Int = myJSON["userId"] as! Int
您应该在访问其值之前检查令牌是否为零。否则应用程序会崩溃。当 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
}
我有一个 JSON 文件,我将其转换为 NSDictionary 对象。我的问题是如何从该对象中获取一个值?我在我的网站上做了一个 httppost,然后我得到一个 JSON 数组返回值 "success" ,"userId" 和 "token i want to check on the "access_token" string in "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;
}
尝试将值转换为 String
var tokenDict: NSDictionary = myJSON["token"] as! NSDictionary
var accessToken: String = tokenDict["access_token"] as! String
对于用户 ID:
var myUserID: Int = myJSON["userId"] as! Int
您应该在访问其值之前检查令牌是否为零。否则应用程序会崩溃。当 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
}