Codable protocol

Codable protocol makes your data types encodable and decodable for compatibility with external representations such as JSON. It is more convenient than JSONSerialization class or SwiftyJSON library.

The simplest way to make a type codable is to declare its properties using types that are already Codable. These types include Swift built-in types and Foundation types like String, Int, Double, URL, Date, Data, Array and Dictionary.

In this case just add Codable protocol to your type.

struct User: Codable {
    var firstName: String
    var lastName: String
}

Convert json string to the object.

let jsonString = """
{
    "firstName": "Harry",
    "lastName":  "Potter"
}
"""

let jsonData = jsonString.data(using: .utf8)!
// convert json string to data with utf8 encoded string

let user = try! JSONDecoder().decode(User.self, from: jsonData)
// convert data to the User object

Convert object to the json string.

var user = User()
user.firstName = "Harry"
user.lastName = "Potter"

let jsonData = try! JSONEncoder().encode(user)
// encode object to the data

let jsonString = String(data: jsonData, encoding: .utf8)!
// convert data to the json string

In some cases, you may not need Codable's support for bidirectional encoding and decoding.

struct Landmark: Encodable {
    var name: String
    var foundingYear: Int
}
struct Landmark: Decodable { var name: String var foundingYear: Int }

Codable types can declare a special nested enumeration named CodingKeys that conforms to the CodingKey protocol. When this enumeration is present, its cases serve as the authoritative list of properties that must be included when instances of a codable type are encoded or decoded.

You can omit propery from enumaration to exclude property form decoding. Or you can specify alternative keys that will be used for encoding and decoding.

struct Landmark: Codable {
    var name: String
    var foundingYear: Int
    var location: Coordinate
    var vantagePoints: [Coordinate]
    
    enum CodingKeys: String, CodingKey {
        case name = "title" // alternative key
        case foundingYear = "founding_date" // alternative key
        
        case location
        case vantagePoints
    }
}