Parsing JSON file with Codable in Swift

Alvar Arias
3 min readFeb 24, 2023

--

Swift language

Introduction

Swift, is a popular programming language for iOS app development, providing built-in support for parsing JSON data.

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is widely used for exchanging data between web servers and mobile apps.

“Codable” protocol, according to the Apple developer documentation :

“The Swift standard library defines a standardized approach to data encoding and decoding. You adopt this approach by implementing the Encodable and Decodable protocols on your custom types. Adopting these protocols lets implementations of the Encoder and Decoder protocols take your data and encode or decode it to and from an external representation such as JSON or property list. To support both encoding and decoding, declare conformance to Codable, which combines the Encodable and Decodable protocols. This process is known as making your types codable.”

This means Codable is the right way to work on tasks involving sending data over a network connection, or submitting data to APIs and services.

Now we can see an example of how to read a JSON file using the “Codable” protocol.

1- First we need a JSON file.

For our example the JSON file at read is :

[
{
"id": "200000",
"name": "the company Name 1",
"organizationNumber": "1111-2222"
},
{
"id": "300000",
"name": "the company Name 2",
"organizationNumber": "1111-3333"
},
{
"id": "400000",
"name": "the company Name 3",
"organizationNumber": "1111-4444"
}
]

2- Create the Codable Structure for parsing in Swift

We create a single Swift file called “organizations.json”, which defines the structure Organization and define Organizations.

import Foundation

// MARK: - Organization Structure

struct Organization: Codable {
let id, name, organizationNumber: String

enum CodingKeys: String, CodingKey {
case id
case name
case organizationNumber
}
}

typealias Organizations = [Organization]

3- Write the JSON Decode function “load” :

func load<T: Decodable>(_ filename: String) -> T {
let data: Data

guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}

do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}

do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}

var myOrganizations: Organizations = load("organizations.json")

This function will parse the file “organizations.json” and if the file is correctly passed the variable Organizations will be an array of organizations.

4- Display the parsed information of the file:

In the first SwiftUI file, read the information in the variable “myOrganizations” and show it by a List, where every “org” in the list is an “Organization” structure of the array.

import SwiftUI

struct ListOrganizationsView: View {

var body: some View {

List(myOrganizations, id: \.id) { org in
ContentView(myorganization: org)
}
}
}

struct ListOrganizationsView_Previews: PreviewProvider {
static var previews: some View {
ListOrganizationsView()
}
}
import SwiftUI


struct ContentView: View {

var myorganization: Organization

var body: some View {

VStack(alignment: .leading){
Text(String(myorganization.name))
Text(String(myorganization.id)).font(.caption)
Text(String(myorganization.organizationNumber)).font(.caption)

}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(myorganization: Organization(id: "1", name: "myOrg", organizationNumber: "12-12"))
}
}

The second SwitUI file displays the Organization elements like text elements.

Conclusion

Is simple and clearly parses a JSON file using a Codable protocol, is also simple to understand and work with it.

Reference: Apple Developer documentation:

--

--

Alvar Arias
0 Followers

IOS Developer, my mantra is please keep it simple and then build big.