Swift parse(Decode) and generate(Encode) JSON data

JSON is pretty much the standard or I would say the most popular option to send and receive data from an API call. So being able to easily encode and decode JSON data is much needed for any application. To  encode and decode JSON data we first create a structure that will define the data we wish to encode from or decode to.

Now to use this structure with the encoder and decoder types, it will need to conform to
the Codable typealias. Codable is a typealias for both Decodable and Encodable protocols.
Using the Encoder and Decoder types makes it very simple to convert to/from JSON objects using JSONEncoder() and  JSONDecoder() functions.

  • JSONEncoder will encode instances of types that conform to the Codable typealias, as JSON objects. 
  • The JSONDecoder type will decode instances of the data type from JSON objects to types that conform to the Codable typealias.  

import UIKit

//Structure to map JSON objects
struct Company: Codable {
    var name: String
    var address: String
    var employee_count: Int
    var stock_listed: Bool
    var employees: [Employee]

struct Employee: Codable {
    var name: String
    var image: String
    var years: Int
    var salary: Double

var employees = [Employee]()
var employee = Employee(name: "Joe",
                        image: "joe.png", years: 12, salary: 110_000.00)
employee = Employee(name: "John",
                    image: "john.png", years: 15, salary: 150_000.00)
employee = Employee(name: "Jake",
                    image: "jake.png", years: 22, salary: 220_000.50)

let company = Company(name: "ABC Company",
                      address: "123 Street, City, State, Zip",
                      employee_count: 3,
                      stock_listed: true,
                      employees: employees)

//Encode Swift Objects to JSON Data String
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try? encoder.encode(company)
if let data = data, let dataString = String(data: data, encoding: .utf8) {

let myJsonData = """
"employee_count" : 3,
"stock_listed" : true,
"name" : "ABC Company",
"employees" : [
"years" : 12,
"name" : "Joe",
"image" : "joe.png",
"salary" : 110000
"years" : 15,
"name" : "John",
"image" : "john.png",
"salary" : 150000
"years" : 22,
"name" : "Jake",
"image" : "jake.png",
"salary" : 220000.5
"address" : "123 Street, City, State, Zip"

//Decode JSON Data String to Swift Objects
if let jsonData = myJsonData.data(using: .utf8) {
    let decoder = JSONDecoder()
    let company = try decoder.decode(Company.self, from: jsonData)
    for employee in company.employees {

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.