DEV Community

Ajithmadhan
Ajithmadhan

Posted on

swift - parse JSON Data from API

JSON stands for JavaScript Object Notation. It’s a popular text-based data format used everywhere for representing structured data. Almost every programming language supports it with Swift being no exception.

In Swift, parsing JSON is a common necessity. Luckily, working with JSON is easy in Swift. It doesn’t even require setting up any external dependencies.

To convert this JSON to a Swift object, let’s store this JSON data in a structure.
To start off, let’s create a structure that conforms to the Decodable protocol to store all the listed properties found in the JSON data:

struct Slip:Codable{ var slip:Advice } struct Advice:Codable{ var id:Int var advice:String } 
Enter fullscreen mode Exit fullscreen mode

Key terms

  • URLSession An object that coordinates a group of related, network data transfer tasks.
  • JSONDecoder An object that decodes instances of a data type from JSON objects.

Creating getSlip function to fetch data from an Url

 let url = "https://api.adviceslip.com/advice" func getSlip(from url:String){ URLSession.shared.dataTask(with: URL(string: url)!, completionHandler:{ data,response,error in guard let data = data else { print("Something went wrong") return } var result:Slip? do{ result = try JSONDecoder().decode(Slip.self,from:data) }catch{ print("Failed decoding data") } guard let json = result else{ return } print("ID: \(json.slip.id)") print("Advice: \(json.slip.advice)") }).resume() } getSlip(from: url) //ID: 134 //Advice: The person who never made a mistake never made anything. 
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ccc_m_bfdfc93e9bbdfc53fbb profile image
ccc M

You can try using SmartCodable for a better experience than Codable.

github.com/intsig171/SmartCodable