Parse JSON response with Swift 3

前端 未结 4 554
我寻月下人不归
我寻月下人不归 2021-01-02 01:08

I have JSON looking like this:

{\"posts\":
    [
    {
    \"id\":\"1\",\"title\":\"title 1\"
    },
    {
    \"id\":\"2\",\"title\":\"title 2\"
    },
             


        
相关标签:
4条回答
  • 2021-01-02 01:16

    DISTANCE--DIFFICULT API ========================>

    class ViewController: UIViewController {
    
        var get_data = NSMutableData()
    
        var get_dest = NSArray()
    
        var org_add = NSArray()
    
        var row_arr = NSArray()
    
    
    
        var ele_arr = NSArray()
    
        var ele_dic = NSDictionary()
    
        var dist_dic = NSDictionary()
    
        var dur_dic = NSDictionary()
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            // Do any additional setup after loading the view, typically from a nib.
    
            getmethod()
    
        }
    
    
    
        func getmethod()
    
        {
    
            let url_str = URL(string: "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&departure_time=1408046331&origins=37.407585,-122.145287&destinations=37.482890,-122.150235")
    
            let url_req = URLRequest(url: url_str!)
    
            let task = URLSession.shared.dataTask(with: url_req) { (data, response, error) in
    
                if let my_data = data
    
                {
    
                   print("my data is----->",my_data)
    
                    do
    
                    {
    
                        self.get_data.append(my_data)
    
                        let jsondata = try JSONSerialization.jsonObject(with: self.get_data as Data, options: [])as! NSDictionary
    
                        print("json data is--->",jsondata)
    
    
    
                self.get_dest = jsondata.object(forKey: "destination_addresses")as! NSArray
    
    
    
                let get_dest1:String = self.get_dest.object(at: 0) as! String
    
                        print("destination is--->",get_dest1)
    
                self.org_add = jsondata.object(forKey: "origin_addresses")as! NSArray
    
    
    
                let get_org:String = self.org_add.object(at: 0)as! String
    
                        print("original address is--->",get_org)
    
    
    
                self.row_arr = jsondata.object(forKey: "rows")as! NSArray
    
                let row_dic = self.row_arr.object(at: 0)as! NSDictionary
    
    
    
                self.ele_arr = row_dic.object(forKey: "elements")as! NSArray
    
    
    
                self.ele_dic = self.ele_arr.object(at: 0)as! NSDictionary
    
    
    
                self.dist_dic = self.ele_dic.value(forKey: "distance")as! NSDictionary
    
                print("distance text is--->",self.dist_dic.object(forKey: "text")as! String)
    
                print("distance value is--->",self.dist_dic.object(forKey: "value")as! Int)
    
    
    
               // self.ele_dic = self.ele_arr.object(at: 1)as! NSDictionary
    
    
    
                self.dur_dic = self.ele_dic.value(forKey: "duration")as! NSDictionary
    
    
    
                print("duration text--->",self.dur_dic.value(forKey: "text")as! String)
    
                print("duration value--->",self.dur_dic.value(forKey: "value")as! Int)
    
    
    
                    print("status---->",self.ele_dic.object(forKey: "status")as! String)
    
    
    
                    }
    
                    catch
    
                    {
    
                        print("error is--->",error.localizedDescription)
    
                    }
    
                }
    
            };task.resume()
    
    
    
        }
    
    0 讨论(0)
  • 2021-01-02 01:21

    In swift 3.0 for GET method:

    var request = URLRequest(url: URL(string: "Your URL")!)        
    
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }
    
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
    
            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
        }
        task.resume()
    

    In swift 3.0 for POST method:

    var request = URLRequest(url: URL(string: "Your URL")!)
    
        request.httpMethod = "POST"
        let postString = "user_name=ABC"  // Your parameter
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }
    
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
    
            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
        }
        task.resume()
    
    0 讨论(0)
  • 2021-01-02 01:23

    Because your data structure of test json should be "[String: AnyObject]". The json key "posts" value is Array type.

    0 讨论(0)
  • 2021-01-02 01:35

    Use this to parse your data:

    let url = URL(string: "http://example.com/file.php")
    URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else { return }
    
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
            let posts = json["posts"] as? [[String: Any]] ?? []
            print(posts)
        } catch let error as NSError {
            print(error)
        }
    }).resume()
    

    Use guard to check if you have data and that error is empty.

    Swift 5.x version

    let url = URL(string: "http://example.com/file.php")
    URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else { return }
    
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
            let posts = json?["posts"] as? [[String: Any]] ?? []
            print(posts)
        } catch {
            print(error)
        }
    }).resume()
    
    0 讨论(0)
提交回复
热议问题