[英]How to parse Json object in swift 3
Hi my question is related to json object. 嗨,我的问题与json对象有关。 i have this link " http://ip-api.com/json " and this link gives the details of your IP Address.
我有此链接“ http://ip-api.com/json ”,此链接提供了您的IP地址的详细信息。 i only need to print IP Address from this json file in swift 3. i am very new might be my question is basic but i need some help to sort out my project.
我只需要在Swift 3中从此json文件中打印IP地址。我很新,可能是我的问题很基本,但是我需要一些帮助来整理项目。 so for i have done like below.
所以因为我已经做了如下。
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()
many thanks in advance. 提前谢谢了。
The IP address is the value for key query
on the top level of the JSON IP地址是JSON顶层密钥
query
的值
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any]
if let query = json["query"] as? String {
print(query)
}
In Swift 3 the type of a JSON dictionary is [String:Any]
在Swift 3中,JSON字典的类型为
[String:Any]
PS: You don't need a URL request for this task, pass the URL directly and use the native structs URL
(and URLRequest
) PS:您不需要此任务的URL请求,直接传递URL并使用本机结构
URL
(和URLRequest
)
let requestURL = URL(string: "http://ip-api.com/json")!
...
let task = session.dataTask(with: requestURL) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.