DEV Community

Ajithmadhan
Ajithmadhan

Posted on

5 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay