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)
employees.append(employee)
employee = Employee(name: "John",
image: "john.png", years: 15, salary: 150_000.00)
employees.append(employee)
employee = Employee(name: "Jake",
image: "jake.png", years: 22, salary: 220_000.50)
employees.append(employee)
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) {
print(dataString)
}
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)
print("===")
print(company.name)
print(company.address)
print(company.stock_listed)
print(company.employee_count)
for employee in company.employees {
print("---")
print(employee.name)
print(employee.salary)
}
}
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.