Parsing JSON object by SWIFT

Today we’ll see how to work with JSON in swift language. We’ll develop a simple currency converter. It will convert USD to Euro by using web API that returns JSON data. Here is the basic structure that we are going to do:
Screen Shot 2014-12-21 at 9.01.36 PM
Let’s begin.
1. Create a new project “CurrencyConverter” and select swift as programming language. Select Single View from next dialog box.

2. Open Main.storyboard and add a textfield, a button and a label. See screenshot for guide. We’ll keep everything simple.

3. Open both Main.storyboard and ViewController.swfit in Assistant editor.

a. Create an IBOutlet for textField and name it txtAmount

b. create an IBOutlet of the label (result) and name it labelResult.

c. Create an IBAction for the button and give it name: actionConvert.

4. Open ViewController.swift in standard editor.

We’ll declare 3 functions (or methods) that will do the following things:

a. getData()
It will get data from server.

b. parseJSON()

This function will convert data received from server into JSON object.

c. displayData()
This function will display the JSON data in UILabel. Call this method inside parseJSON method.

Finally in actionConvert method (or function), call getData and parseJSON.

Run the application to see the result.


IMPORTANT NOTE: If you want to fetch JSON Array instead of JSON Object (One JSON array contains one or more JSON objects), please use the following method: 

Leave a Reply