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()
Author by
user3051755
Updated on July 09, 2022Comments
-
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 over 7 yearsI 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 gettext
andresponse
values? Thanks -
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 over 7 yearsThanks, now it works for
posts
! How can I also get values oftext
andresult
? I triedlet text = json["text"] as? [String: String] print(text)
but it printsnil
as a result. -
Rashwan L over 7 yearsTry let json["text"] as? String
-
User over 7 yearsWarning:
Cast from '[String : Any]' to unrelated type '[[String : Any]]' always fails
-
Rashwan L about 7 years@krummens, what doesn´t work for you? What error do you get?
-
krummens about 7 yearsI 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 almost 5 yearsHow to take individual values using get method ... like taking id 2 value?