12

I have JSON looking like this:

{"posts":
    [
    {
    "id":"1","title":"title 1"
    },
    {
    "id":"2","title":"title 2"
    },
    {
    "id":"3","title":"title 3"
    },
    {
    "id":"4","title":"title 4"
    },
    {
    "id":"5","title":"title 5"
    }
    ],
    "text":"Some text",
    "result":1
}

How can I parse that JSON with Swift 3?

I have this:

let url = URL(string: "http://domain.com/file.php")!
let request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data else {
        print("request failed \(error)")
            return
    }

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
            // Parse JSON
        }
    } catch let parseError {
        print("parsing error: \(parseError)")
        let responseString = String(data: data, encoding: .utf8)
            print("raw response: \(responseString)")
        }
    }
    task.resume()
}

4 Answers 4

28

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()
Sign up to request clarification or add additional context in comments.

7 Comments

I get empty response in app. ...2016-10-09 05:02:28.148947 App Name[15760:381303] [] tcp_connection_get_statistics DNS: 16ms/29ms since start, TCP: 178ms/223ms since start, TLS: 0ms/0ms since start [:]. Do you also know how to get text and response values? Thanks
@user3051755, posts return an array of dictionaries (see your json) so I updated let posts = json["posts"] as? [[String: Any]] ?? []. Try the new code instead and it should work for you.
Thanks, now it works for posts! How can I also get values of text and result? I tried let text = json["text"] as? [String: String] print(text) but it prints nil as a result.
Try let json["text"] as? String
Warning: Cast from '[String : Any]' to unrelated type '[[String : Any]]' always fails
|
6

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()

1 Comment

How to take individual values using get method ... like taking id 2 value?
0

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

Comments

-5

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()



    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.