I am a newbie to parsing JSON and using Restful API. Whatevs, i have been looking a lot for this issue and I found lots of. But I couldn't figure it out.
JSON that I want to parse is: http://jsonplaceholder.typicode.com/users
guard let url = URL(string: "http://jsonplaceholder.typicode.com/users/") else {return}
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error ?? "")
}
if data != nil {
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves)
guard let idk = json as? [Dictionary<String, Any>] else {return}
print(idk)
}
catch{
print(error)
}
}
}.resume()
I came untill here and I can't move on. For example I'd like to reach id, name and username but I dont know what to do anymore. And Im wonder what if I'd like to dive into the dictionary of Adress ?
This is an example how you can read the data:
for data: Dictionary<String, Any> in idk{
if let address = data["address"] as? Dictionary<String, Any>{
//here the data in address: { .. } is available
//for example
print(address["city"] ?? "")
}
//or id
print(data["id"] ?? "")
//username
print(data["username"] ?? "")
}
Alper, why don't you use SwiftyJSON to do this. Download the cocoa pod and follow instructions on their Github page: https://github.com/SwiftyJSON/SwiftyJSON
Parsing then becomes very simple. It would appear that in Swift 4, JSON is handled much better and libraries like SwiftyJSON won't be required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With