swift decode json within decoded json code example

Example 1: JSONDecoder

struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let json = """
{
    "name": "Durian",
    "points": 600,
    "description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)

print(product.name) // Prints "Durian"

Example 2: json decoding and optionals

struct BlogPost: Decodable {
    let title: String
    /// Define a key as optional if it can be returned as `nil` or if it does not always exist in the JSON.
    let subtitle: String?
}