Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON response with Swift 3

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()
}
like image 739
user3051755 Avatar asked Oct 09 '16 01:10

user3051755


1 Answers

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()
like image 69
Rashwan L Avatar answered Oct 14 '22 17:10

Rashwan L