2017-10-11 213 views
0

我該如何解析這個JSON?swift從URL解析JSON

{ 
    "telefon":"05538690671" 
} 

我的代碼:

let url = NSURL(string: "http://localhost.192.168.1.40.xip.io:8888/store1.php") 

    //fetching the data from the url 
    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in 

     if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary { 

      //printing the json in console 
      print(jsonObj!.value(forKey: "telefon")!) 

對不起我的英語

回答

0

我清理了一點東西,與guard降NS的東西和保護的結果。

let url = URL(string: "http://localhost.192.168.1.40.xip.io:8888/store1.php")! 

URLSession.shared.dataTask(with: url) { data, _, _ in 
    guard let data = data else { return } 
    guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else { return } 
    guard let jsonObj = json as? [String: Any] else { return } 

    guard let telefon = jsonObj["telefon"] as? String else { return } 

    print(telefon) 
} 

多一點的調試。

let url = URL(string: "http://localhost.192.168.1.40.xip.io:8888/store1.php")! 

URLSession.shared.dataTask(with: url) { data, _, _ in 
    guard let data = data, !data.isEmpty else { 
     print("Error: data is nil or empty") 
     return 
    } 

    guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else { 
     print("Error: data contains no JSON") 
     return 
    } 

    guard let jsonObj = json as? [String: Any] else { 
     print("Error: JSON is not a dictionary") 
     return 
    } 

    guard let telefon = jsonObj["telefon"] as? String else { 
     print("Error: Object has no 'telefon' key") 
     return 
    } 

    print(telefon) 
} 
+0

遺憾,當我從跟蹤這個dataTask跳碼到結束的代碼 –

+0

@ÜmitGündüz這意味着的'guard'條件之一已經失敗。 –

+0

@ÜmitGündüz我添加了一個新版本,在某些失敗情況下調試更多。 –

0

使用Alamofire(https://github.com/Alamofire/Alamofire)來獲取數據。

將Alamofire添加到您的項目中。

自定義類來解析

import UIKit 
    import Alamofire 

    typealias DownloadComplete =() ->() 

    class YourClassName { 

    private var _telefon: String! 

    var telefon: String { 
      if _telefon == nil { 
       _telefon = "" 
      } 
      return _telefon 
     } 

    func downloadDetails(completed: @escaping DownloadComplete) { 
      let currentURL = URL(string: "http://localhost.192.168.1.40.xip.io:8888/store1.php")! 
      Alamofire.request(currentURL).responseJSON { response in 
       let result = response.result 
      if let dict = result.value as? Dictionary<String, AnyObject> { 
       if let telefon = dict["telefon"] as? String { 
       self._telefon = telefon 
       } 
      } 
      } 
     completed() 
    } 
}