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

标签 json swift

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

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

它总是将结果分配为可选

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()
}

最佳答案

在尝试通过字符串插值使用它之前,您需要解包可选。最安全的方法是通过可选绑定(bind):

请使用以下适合您的代码。

  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)
                }
            }
        }

关于json - Swift 没有从 JSON 结果中分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44966085/

相关文章:

Javascript:如何将对象的 JSON 数组转回对象类型共享原型(prototype)?

iphone - Json 解析 objective-c 中的 nil 字段

ios - 无法从 Parse 对象检索 createdAt 值

ios - 像表格一样显示具有动态大小的标签,但不重叠

ios - CoreData - 安全检查 CoreData 对象的值

ios - 如何在文件管理器中保存多个图像

java - 使用 MongoDB for Authzforce 将 XACML 文件存储在 JSON 中

javascript - 下拉组件填充数据,只有虚拟数据有效

javascript - 如何使用双for循环从json中检索过滤后的数据

ios - UICollectionView:如何在不长按的情况下重新排序