fbpx
How to parse JSON with SwiftyJSON in iOS using Swift

How to parse JSON with SwiftyJSON in iOS using Swift

Today, I’m going to show you how to use the 3rd party library SwiftyJSON to parse JSON your iOS app.

You can use SwiftyJSON alongside Alamofire or URLSession to handle the HTTP requests and get the JSON data from the server.

If you don’t know how to make HTTP requests, I recently wrote how to do it in both: Alamofire and URLSession

In this tutorial, I’ll cover 3 cases that may you face when you’re trying to parse JSON:

  • Simple JSON: Just a simple JSON without any complex structure
  • Array JSON: The JSON structure begins with an array and without a key
  • Nested JSON: Includes nested objects

Adding the library

In this example, we are going to add the SwiftyJSON library into our project using Cocaopods.

Open your Podfile with your favorite text editor (e.g., Visual Studio Code) and add pod 'SwiftyJSON'

Add SwiftyJSON in your Podfile

Then, run pod update in the terminal

Do pod update to install SwiftyJSON in your iOS project

Simple JSON

A simple JSON doesn’t have any complex structure, like arrays, nested objects e.t.c, and it looks like that:

{
    "id": "1",
    "employee_name": "Jack Full",
    "employee_salary": "300800",
    "employee_age": "61"
}

To parse it with SwiftyJSON, you just take the data after the HTTP request, and then:

let json = try! JSON(data: data)

// ID
let id = json["id"].string ?? "N/A"
print("ID: \(id)")

// Employee Name
let employeeName = json["employee_name"].string ?? "N/A"
print("Employee Name: \(employeeName)")

// Employee Salary
let employeeSalary = json["employee_salary"].string ?? "N/A"
print("Employee Salary: \(employeeSalary)")

// Employee Age
let employeeAge = json["employee_age"].string ?? "N/A"
print("Employee Age: \(employeeAge)")

Array JSON

JSON uses arrays to create a list of data. Some of them start with an array but without a key:

[
    {
        "id": "1",
        "employee_name": "Tiger Nixon",
        "employee_salary": "320800",
        "employee_age": "61"
    },
    {
        "id": "2",
        "employee_name": "Garrett Winters",
        "employee_salary": "170750",
        "employee_age": "63"
    },
    // ...
]

In this case, with SwiftyJSON, using the data from the HTTP request, you can parse it like this:

let json = try! JSON(data: data)

let arrayCount = json.array?.count ?? 0
for i in 0..<arrayCount {
    // ID
    let id = json[i]["id"].string ?? "N/A"
    print("ID: \(id)")
    
    // Employee Name
    let employeeName = json[i]["employee_name"].string ?? "N/A"
    print("Employee Name: \(employeeName)")
    
    // Employee Salary
    let employeeSalary = json[i]["employee_salary"].string ?? "N/A"
    print("Employee Salary: \(employeeSalary)")
    
    // Employee Age
    let employeeAge = json[i]["employee_age"].string ?? "N/A"
    print("Employee Age: \(employeeAge)")
    
    
    // Save data using your Model
    
    // Reload data of TableView/CollectionView
}

Nested JSON

When a JSON object is inside another JSON object, it’s called ‘nested’, and will look like the following JSON structure:

{
    "data": [
        {
            "id": "1",
            "employee": {
                "name": "Tiger Nixon",
                "salary": {
                    "usd": 320800,
                    "eur": 273545
                },
                "age": "61"
            }
        },
        {
            "id": "2",
            "employee": {
                "name": "Garrett Winters",
                "salary": {
                    "usd": 170750,
                    "eur": 145598
                },
                "age": "63"
            }
        },
        // ...
    ]
}

To parse this complex JSON nesting of objects and array with SwiftyJSON, you just take the data after the HTTP request, and then:

let json = try! JSON(data: data)
for (_, data) in json["data"] {
    // ID
    let id = data["id"].string ?? "N/A"
    print("ID: \(id)")
    
    // Employee Name
    let employeeName = data["employee"]["name"].string ?? "N/A"
    print("Employee Name: \(employeeName)")
    
    // Employee Salary in USD
    let employeeSalaryUSD = data["employee"]["salary"]["usd"].int ?? 0
    print("Employee Salary in USD: \(employeeSalaryUSD)")
    
    // Employee Salary in EUR
    let employeeSalaryEUR = data["employee"]["salary"]["eur"].int ?? 0
    print("Employee Salary in EUR: \(employeeSalaryEUR)")
    
    // Employee Age
    let employeeAge = data["employee"]["age"].string ?? "N/A"
    print("Employee Age: \(employeeAge)")
    
    // Save data using your Model
    
    // Reload data of TableView/CollectionView
}
You can find the final project here

If you have any questionsplease feel free to leave a comment below

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments