0

Share

APP DEVELOPMENT

How To Parse JSON From Files & URLs In Swift 4.2?

  • Home
  • Blogs
  • How To Parse JSON From Files & URLs In Swift 4.2?

JavaScript Object Notation (JSON) is a data-interchange format, and JSON Parsing is the conversion of a JSON object in text format to a JavaScript object.

Somish Kakadiya

July 21, 2022

While developing many applications, you may have already come across iOS development, so while you are trying to access data using URL Session, this is where JSON files come in. 

JSON in Swift is also known as SwiftyJSON. It is a library that helps to read and process JSON data from an API or server. Swift is strict about data types and wants the user to explicitly declare them, but JSON is usually implicit about data types. Hence, you need to learn how to parse JSON from files and URLs in Swift 4.2. Have a look at the process.

Creating An Example Project

Open and Run Xcode and create a new project with File » New » Project ⌘⇧N. Select iOS » Application » Single View Application:

Here, there will be two methods to load JSON Data one way will be through the .json file which will be stored in out project folder and other way is to parse JSON from URL.

Now, create one global variable for JSON data type it’s “file” or “url”. For that put below line in ViewDidLoad() and will create a variable of NSMutableArray() type to store JSON Data:

Add JSON File To Your Project




To fetch JSON data, we have to copy the days.json file into our project repository. Which contains following JSON format data.

Here is the JSON that we will be parsing.

How To Parse JSON Using File

Following methods explains how to convert JSON file into NSData.

Then pass those data object in NSJSONSerialization method JSONObjectWithData:options:error. That should return array or dictionary as per JSON format.

func getFromFile() { let path: NSString = Bundle.main.path(forResource: "days", ofType: "json")! as NSString let data : NSData = try! NSData(contentsOfFile: path as String, options: NSData.ReadingOptions.dataReadingMapped) self.startParsing(data: data) }

How To Parse JSON Using URL




Following method describes how to convert JSON file into NSData for web url JSON data:

  • Lets create a variable named “url” which will consist of the json file web url.
  • Then, by using NSURLRequest we will use url to get JSON file data.

How To Get JSON Data And Store It

By using following startParsing (data:) method,

  • We are also going to create another constant called dict as part of the condition.
  • We are also going to use try as it may throw an error and this will be of type NSJSONSerialization using the object JSONObjectWithData().
  • We will pass our constant data into the object as well. We also have the possibility to pass in options.
  • We have got dict which consist of JSON data as dictionary, so get the particular data we need to get that through its key.
  • As, we have two dictionaries called “Marvel” and “DC”, we will use for loop to get each data from both dictionaries.
  • Need to save that data in arrayDict which we have declared earlier.

Show JSON Data Into TableView




We need to set delegate and datasource of TableView. Following line of code shows how to set delegate and data source for table view.

In ViewController.swift file write following line of code. You can set delegate and datasource from TableView by dragging TableView to viewcontroller icon also like below.

Create Custom Tableview Cell




Select Project folder and do right click then select new file -> Cocoa Touch Class -> select UITableViewCell as subClass and give suitable name for file as shown below.

Your Custom Cell file is created and ready to use, we will create three Label outlet of to show data for movie name, description and lead role.

It should look like this:

TableView Delegate Methods




Following below are the table view delegate methods that display parsed JSON formatted data.

Following line of code you need to put in ViewController.swift file.

numberOfSectionsInTableView(tableView : ) method is used to display sections.

Here we have only one section to display so return will be 1.

  • numberOfRowsInSection method is used to show number of rows in particular section.
  • Here the number of rows will depend on number of array elements so return will be arrayDict.count.

Cellforrowat method is used to show the data in tableview, we will use customCell file with identifier “cell”, then by using the dictionary key will get the data from dictionary and store it in particular variable and pass that variable in Label text.

Final OutPut




Conclusion

This blog is wrapped with JSON parsing from files and URLs in Swift, which is also known as SwiftyJSON. 

JSON is a readable format for structuring data that is used to transmit data between servers and web applications as an alternative to XML.JSON. This JavaScript-based language will be helpful to you while working with Swift.


img

Somish Kakadiya

CTO of Vasundhara Infotech, a leading Software development company in the USA. His technological interests has helped the company in making useful decisions.

message

Have a project in mind? Drop a message to Bansi Pipaliya & start the discussion!

Get a Newsletter

Sign Up to our newsletter to get latest updates staight in your inbox.

Vasundhara respects your privancy. No Spam!

Get a Newsletter

Sign Up to our newsletter to get latest updates staight in your inbox.

Vasundhara respects your privancy. No Spam!

message

Have a project in mind? Drop a message to Bansi Pipaliya & start the discussion!

Latest 13 Web Development Trends To Expect In 2022
April 11, 2022 Category : company news

Revealing Vasundhara’s New Identity

Read More
Latest 13 Web Development Trends To Expect In 2022
May 17, 2022 Category : web development

Latest 13 Web Development Trends To Expect In 2022

Read More
Leave a Comment