Swift没有从JSON结果中分配变量

时间:2017-07-07 08:29:21

标签: json swift

我在swift(php连接)中加载JSON结果时遇到了问题。

我可以检索JSON数据,但不允许我将其分配给变量。

它始终将结果指定为Optional

JSON数据:

{
"country": [{
    "id": 1,
    "name": "Australia",
    "code": 61
}, {
    "id": 2,
    "name": "New Zealand",
    "code": 64
}]
}

xCode输出:

 ["country": <__NSArrayI 0x60000002da20>(
 {
     code = 61;
     id = 1;
     name = Australia;
 },
 {
     code = 64;
     id = 2;
     name = "New Zealand";
 }
 )
 ]
 Country Name: Optional(Australia)
 Country Name: Optional(New Zealand)

.swift文件:

//function did_load
override func viewDidLoad() {
    super.viewDidLoad()

    //created RequestURL
    let requestURL = URL(string: get_codes)

    //creating NSMutable
    let request = NSMutableURLRequest(url: requestURL!)

    //setting the method to GET
    request.httpMethod = "GET"

    //create a task to get results
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil{
            print("error is \(String(describing: error))")
            return;
        }

        //lets parse the response
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
            print(json)
            if let countries = json["country"] as? [[String: AnyObject]] {
                for country in countries {
                    print("Country Name: \(String(describing: country["name"]))")
                    print("Country Code: \(String(describing: country["code"]))")
                    if let couname = country["name"] as? [AnyObject] {
                        print(couname)
                    }

                    if let coucode = country["code"] as? [AnyObject] {
                        print(coucode)
                    }
                }
            }
        } catch {
            print("Error Serializing JSON: \(error)")
        }
    }
    //executing the task
    task.resume()
}

1 个答案:

答案 0 :(得分:3)

在尝试通过字符串插值使用之前,需要打开可选项。最安全的方法是通过可选绑定:

请使用以下代码,这对您有用。

  if let countries = json["country"] as? [[String: AnyObject]] {
            for country in countries {
                print("Country Name: \(country["name"] as! String)")
                print("Country Code: \(country["code"] as! String)")
                if let couname = country["name"] as? String {
                    print(couname)
                }

                if let coucode = country["code"] as? Int {
                    print(coucode)
                }
            }
        }