Last active
August 31, 2018 22:06
-
-
Save juanbrusco/af1c0b40a84258791e317aaceac3d674 to your computer and use it in GitHub Desktop.
Parsing json objects - Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//JSON example | |
{ | |
"ObjectList": [ | |
{ | |
"x": "Starbucks", | |
"y": "asd" | |
}, | |
{ | |
"x": "Starbucks", | |
"y": "asd" | |
} | |
] | |
} | |
// | |
struct Object: Codable { | |
var x: String | |
var y: String | |
} | |
struct ObjecttList: Decodable { | |
let objects : [Object] | |
} | |
var result:ObjecttList? | |
let jsonUrlString = "http://www.json-generator.com/api/json/get/cfpSCkOGjS?indent=2" | |
guard let url = URL(string: jsonUrlString) else {return} | |
URLSession.shared.dataTask(with: url) { (data, response, err) in | |
guard let data = data else {return} | |
do { | |
let articlesData = try JSONDecoder().decode(ObjecttList.self, from: data) | |
DispatchQueue.main.async { | |
self.result = articlesData | |
} | |
} catch let jsonErr { | |
print("Error serializing json", jsonErr) | |
} | |
}.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better and complete example:
https://mrgott.com/swift-programing/33-rest-api-in-swift-4-using-urlsession-and-jsondecode