2016-11-02 154 views
0

您好,我的問題與json對象有關。我有這個鏈接「http://ip-api.com/json」,這個鏈接給出了你的IP地址的詳細信息。我只需要在swift 3中打印來自這個json文件的IP地址。我很新可能是我的問題很基本,但我需要一些幫助來整理我的項目。所以我做了如下。如何快速解析Json對象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() 

非常感謝提前。

回答

0

的IP地址是在JSON的頂級關鍵query

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

在斯威夫特3 JSON字典的類型是[String:Any]

PS:你並不需要一個這個任務的URL請求,直接傳遞的網址,並使用原生結構URL(和URLRequest

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

非常感謝在幹活很棒! –

+0

然後請接受答案,點擊複選標記。 (OT:我住在Altnau附近) – vadian

+0

謝謝我接受了你的回答。 –