Swift-1: Parsing JSON

Bo-Kai
4 min readMar 15, 2021

Recently, I have learned how to parse a json file in Xcode or using Swift. As a result, I think it’s better that I put it down to reinforce my memory.

JSON is short for JavaScript Object Notation. It is a lightweight format for storing and transporting data. It is often used when data is sent from a server to a web page. The following are some basic features of JSON.

  1. {}(pronounced as curly brackets) represents JSON Object. key is always a string while value can be any data type.
    For example,
    {
    “name”= ”Shelby”,
    “age” = 29,
    “likes” = “Pizza”
    }

2. [](pronounced as square brackets) represents JSON Array.

3. A comma is used to separate elements in a JSON array or separating key-value pairs in a JSON object.

An JSON array containing two JSON objects would be like,

[
{“name”:”Shelby”,
“age” :29,
“likes”:“Pizza”
},
{“name”:”Tom”,
“age”:19,
“likes”:“Burrito”
}
]

handy website to validate your json code.
JSONLint

How do we parse a local JSON file in Xcode?

A) Create or import a json file to the same project.

We can create a new folder to store the json file, which is good for management.

Remember to create a class/struct that contains the same properties and data types as those in the json file. For example, our json file contains the following key-value pairs.

So, our question class needs to have question, answers, correctAnswerIndex, and feedback properties. In fact, we don’t need to include all the keys included in the json object. We can only take what we need. However, the the spelling of the property names have to be identical to those in the json object.

B) Get a path to the json file within the project.

Bundle.main.path(forResource: , ofType: ) method is used to get the path. “forResource” indicates the name of the file, and “ofType” indicates the extension of the file. Therefore, the file name is “QuestionData” and the extension is “json”.

C) Create a url object.

URL(fileURLWithPath:) is used to created the url object. We just need to pass the path to “fileURLWithPath” .

D) Create a data object with our data stored in the url object. Data(contentsOf:) method is used to create the data object(, which may throw an error, so we need to use do-catch block. We will not talk about this.)

E) Parse the data object into the desired instances. There are two steps.
E1) Create a JSON decoder object using JSONDecoder().
E2) Call the decode method on the JSON decoder object.
decoder.decode(type: Decodable.Protocol, from data: ) method is called(, which may throw an error). In type argument, we need to specifiy what kind of type the json file is intended to be converted to. In from argument, we need to specify the data object we are using, which is also named data.
Remember that when you call the decode method, Xcode may tell you that the class/struct needs to conform to decodable or codable protocol. In this case, our question class/struct needs to conform to decodable or codable protocol.

How do we parse a remote JSON file in Xcode?

A) Get a url object.

First, we need to get the url to the json file, and then use it to create a url object. This time, however, we use URL(string:) to create a url object.

B) Get a data task object.

There are two similar methods. In this case, we call the method that takes a URL. Then, double clicking the closure, it will open a trailing closure as follows.

For, the arguments, we only need to give them names, and it will automatically pass the values to them.

C) Start parsing the JSON file in the completion handler closure.

Finally, when we are done with all the above coding, the dataTask object simply contains the information. It doesn’t go to that URL and download the JSON file. According to the discussion of resume method in Apple Developer Documentation, newly-initialized tasks begin in a suspended state, so you need to call this method to start the task. Therefore, we need to call resume method on dataTask to tell the dataTask object to start the task.

--

--