简体   繁体   中英

How to get specific JSON in Xcode 8 Swift 3.0 using Alamofire?

I have these JSON data

{
    "ID":"ID01",
    "pass":"1234",
    "mail":"email@g.com"
}

I'm trying to display ID only using Alamofire, all JSON object can be print it out.

But when i try to print specifically, an error appears "type 'Any' has no subscript members" on line

print(JSON["ID"] as! String)

The code as below

import UIKit
import Alamofire
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request("http://localhost/get.php").responseJSON
            { response in

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                    print(JSON["ID"] as! String)
                }
            }   
    }
}

You should try to cast value of the response.

How about:

if let JSON = response.result.value as? [String : Any]{
    print("JSON: \(JSON)")
    if let id = JSON["ID"] as? String {
        print(JSON["ID"])
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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