我有一个 JSON 文件,我将其转换为 NSDictionary 对象。我的问题是如何从该对象中获取一个值?我在我的网站上创建了一个 httppost,然后我得到了一个 JSON 数组,其中包含值“success”和“userId”我想检查成功是真还是假。
import UIKit
class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func HttpBtn(sender: AnyObject) {
PostToServer()
HttpPost()
}
func PostToServer()
{
println("Button Presed")
}
func HttpPost()
{
var postString = "email=joakim@and.dk&password=123456"
//Declare URL
var url: NSURL! = NSURL(string: "http://95.85.53.176/nhi/api/app/login")
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
//Declare which HTTPMethod
request.HTTPMethod = "POST"
//POST data
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
println("response =\(response)")
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString =\(responseString)")
var error: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &error) as? NSDictionary
println(myJSON)
}
task.resume()
}
}
输出
responseString =Optional({"success":true,"userId":"62"})
Optional({
success = 1;
userId = 62;
})
最佳答案
您可以使用它的键值访问
var success = myJSON["success"]!.intValue
var userId = myJSON["userId"]!.intValue
if(success == 1) //if true
{
//Do something
}
与userId
相同
关于json - 在 Swift 中从 JSON 文件中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31832698/