如何快速parsingJson对象3
您好我的问题是关于json对象。 我有这个链接“ http://ip-api.com/json ”,这个链接给出了你的IP地址的详细信息。 我只需要从这个json文件打印IP地址在swift 3.我很新可能是我的问题是基本的,但我需要一些帮助来整理我的项目。 所以我做了如下。
let requestURL: NSURL = NSURL(string: "http://ip-api.com/json")! let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL) let session = URLSession.shared let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) -> Void in let httpResponse = response as! HTTPURLResponse let statusCode = httpResponse.statusCode if (statusCode == 200) { print("Everyone is fine, file downloaded successfully.") do{ let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject] if let stations = json["city"] as? [[String: AnyObject]] { for station in stations { if let name = station["regionName"] as? String { self.names.append(name) print("this is query\(name)") } else{ print ("no ip address is found") } } } } catch { print("Error with Json: \(error)") } } } task.resume()
提前谢谢了。
IP地址是JSON顶级密钥query
的值
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any] if let query = json["query"] as? String { print(query) }
在Swift 3中,JSON字典的types是[String:Any]
PS:您不需要此任务的URL请求,直接传递URL并使用本地结构URL
(和URLRequest
)
let requestURL = URL(string: "http://ip-api.com/json")! ... let task = session.dataTask(with: requestURL) {