如何在Swift 3中解析Json对象 [英] How to parse Json object in swift 3

查看:81
本文介绍了如何在Swift 3中解析Json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与json对象有关.我有此链接" http://ip-api.com/json ",此链接为您的IP地址的详细信息.我只需要在swift 3中从此json文件中打印IP地址.我很新,可能是我的问题很基本,但是我需要一些帮助来整理项目.所以因为我做了如下.

Hi my question is related to json object. i have this link "http://ip-api.com/json" and this link gives the details of your IP Address. 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. 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()

非常感谢.

推荐答案

IP地址是JSON顶级上的键query的值

The IP address is the value for key query on the top level of the JSON

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any]
if let query = json["query"] as? String {
  print(query)
}

在Swift 3中,JSON字典的类型为[String:Any]

In Swift 3 the type of a JSON dictionary is [String:Any]

PS:此任务不需要URL请求,直接传递URL并使用本机结构URL(和URLRequest)

PS: You don't need a URL request for this task, pass the URL directly and use the native structs URL (and URLRequest)

let requestURL = URL(string: "http://ip-api.com/json")!
...
let task = session.dataTask(with: requestURL) {

这篇关于如何在Swift 3中解析Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆