JSONDecoder
An object that decodes instances of a data type from JSON objects.
Declaration
class JSONDecoderOverview
The example below shows how to decode an instance of a simple GroceryProduct type from a JSON object. The type adopts Codable so that it’s decodable using a JSONDecoder instance.
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"