ahcode0919
6/6/2017 - 10:53 PM

Swift 4 Codable example (Type -> JSON)

Swift 4 Codable example (Type -> JSON)

//Simple Type - Person
struct Person: Codable {
    let name: String
    let age: Int
    
    func getString() -> String {
        return "Name: \(name), Age: \(age)"
    }
}

//Create Person Struct
let person = Person(name: "Aaron", age: 33)
print("Original Person Struct: " + person.getString() + "\n")

//Encode Person Struct as Data
let encodedData = try? JSONEncoder().encode(person)

//Create JSON
var json: Any?
if let data = encodedData {
    json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
}

//Print JSON Object
if let json = json {
    print("Person JSON:\n" + String(describing: json) + "\n")
}

//Convert JSON back to Data
var jsonData: Data?
if let json = json {
    jsonData = try? JSONSerialization.data(withJSONObject: json)
}

//Convert JSON Data back to Person Struct
var decodedPerson: Person?
if let data = jsonData {
    decodedPerson = try? JSONDecoder().decode(Person.self, from: data)
}

//Print Person Struct
if let decodedPerson = decodedPerson {
    print("Decoded Person Struct: " + decodedPerson.getString())
}

/*
 Output:
 
 Original Person Struct: Name: Aaron, Age: 33
 
 Person JSON:
 {
 age = 33;
 name = Aaron;
 }
 
 Decoded Person Struct: Name: Aaron, Age: 33
 */

//Nested Type Abbreviated Example
struct Family: Codable {
    let familyName: String
    var familyMembers: [Person]
    
    init(familyName: String, familyMembers: [Person] = [Person]()) {
        self.familyName = familyName
        self.familyMembers = familyMembers
    }
    
    mutating func addFamilyMember(relative person: Person) {
        familyMembers.append(person)
    }
}

let mother = Person(name: "Arlene", age: 35)
let father = Person(name: "Calvin", age: 36)

var family = Family(familyName: "Hinton")
family.addFamilyMember(relative: mother)
family.addFamilyMember(relative: father)

print("\n\n***Encoding and Decoding complex types***\n")
print("Family Struct")
for person in family.familyMembers {
    print("Family Member: " + person.getString())
}

//Encode Family Struct as Data
let familyData = try? JSONEncoder().encode(family)

//Create JSON
var familyJson: Any?
if let data = familyData {
    json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
}

//Print JSON Object
if let json = json {
    print("\nFamily JSON:\n" + String(describing: json) + "\n")
}

//Convert JSON back to Data
if let json = json {
    jsonData = try? JSONSerialization.data(withJSONObject: json)
}

//Convert JSON Data back to Person Struct
var decodedFamily: Family?
if let data = jsonData {
    decodedFamily = try? JSONDecoder().decode(Family.self, from: data)
}

//Print Family Struct
print("\nDecoded Family Struct:")
if let decodedFamily = decodedFamily {
    for person in decodedFamily.familyMembers {
        print("Family Member: " + person.getString())
    }
}

/*
 Output:
 
 ***Encoding and Decoding complex types***
 
 Family Struct
 Family Member: Name: Arlene, Age: 35
 Family Member: Name: Calvin, Age: 36
 
 Family JSON:
 {
     familyMembers =     (
         {
             age = 35;
             name = Arlene;
         },
         {
             age = 36;
             name = Calvin;
         }
     );
     familyName = Hinton;
 }
 
 Decoded Family Struct:
 Family Member: Name: Arlene, Age: 35
 Family Member: Name: Calvin, Age: 36
 */