Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Parsing JSON Using Codable An Overview of Codable The Encodable Protocol

Why does the size of JSON change?

import Foundation

let json = """
    "name": "Pasan",
    "id": 1,
    "role": "Teacher"
""".data(using: .utf8)! // this is 59 bytes

struct Employee: Codable {
    let name: String
    let id: Int
    let role: String

    enum CodingsKeys: String, CodingKey {
        case name = "name"
        case id = "id"
        case role = "role"

    init(form decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.id = try container.decode(Int.self, forKey: .id)
        self.role = try container.decode(String.self, forKey: .role)

let decoder = JSONDecoder()
let employee = try! decoder.decode(Employee.self, from: json)

let encoder = JSONEncoder()
let encodedEmployee = try! encoder.encode(employee) // this is 40 bytes

But when we decode it do employee and then back to JSON the size decreases to 40 but not back to 59 why is this?

1 Answer

Chris Stromberg
Chris Stromberg
Courses Plus Student 13,389 Points

You have a lot of whitespace around your initial JSON object.

let json = """
""".data(using: .utf8)! // this is 40 bytes