【问题标题】:Swift is not assigning variables from JSON resultsSwift 没有从 JSON 结果中分配变量
【发布时间】:2017-07-07 08:29:20
【问题描述】:

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

【问题讨论】:

  • 字典下标返回一个可选值,例如参见stackoverflow.com/questions/25979969/…(或 Swift 语言参考)。 country["name"] as? [AnyObject] 没有意义,因为该值是字符串,而不是数组。
  • 请注意,String(describing:) 几乎从不您想要什么,并隐藏了实际的类型问题。
  • @RAJAMOHAN-S:反引号用于code,不是一般强调。没有理由将“JSON”格式化为JSON 或将“变量”格式化为variable
  • @MartinR,好的,谢谢兄弟 :) 我注意到了。

标签: json swift


【解决方案1】:

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

请使用下面的代码,这对你有用。

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

【讨论】:

  • 这会引发以下错误“使用未解析的标识符'responce'”
  • 用json替换响应
  • Swift 3 中的 JSON 字典是 [String:Any]
猜你喜欢
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 2019-12-07
  • 2021-02-04
  • 1970-01-01
  • 2016-04-15
  • 2015-08-22
  • 2023-01-08
相关资源
最近更新 更多