Parse JSON response with Swift 3

51,762

Solution 1

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

Solution 2

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()
Share:
51,762
user3051755
Author by

user3051755

Updated on July 09, 2022

Comments

  • user3051755
    user3051755 almost 2 years

    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()
    }
    
  • user3051755
    user3051755 over 7 years
    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
  • Rashwan L
    Rashwan L over 7 years
    @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.
  • user3051755
    user3051755 over 7 years
    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.
  • Rashwan L
    Rashwan L over 7 years
    Try let json["text"] as? String
  • User
    User over 7 years
    Warning: Cast from '[String : Any]' to unrelated type '[[String : Any]]' always fails
  • Rashwan L
    Rashwan L about 7 years
    @krummens, what doesn´t work for you? What error do you get?
  • krummens
    krummens about 7 years
    I have json response similar to OP, but this is the response I am getting: Could not cast value of type '__NSArrayI' (0xea76d0) to 'NSDictionary' (0xea7928).
  • vamsi
    vamsi almost 5 years
    How to take individual values using get method ... like taking id 2 value?