JSON κ°μ²΄μμ λ°μ΄ν° μ νμ μΈμ€ν΄μ€λ₯Ό λμ½λ©νλ κ°μ²΄
// λ€μ μμ λ JSON κ°μ²΄μμ κ°λ¨ν GroceryProduct μ νμ μΈμ€ν΄μ€λ₯Ό λμ½λ©νλ λ°©λ²
// ν΄λΉ μ νμ Codableμ μ±ννμ¬ 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"
κΈ°λ³Έ νμ μ€μ κ³Ό λμ½λ© μ λ΅μ μ¬μ©νμ¬ μλ‘μ΄ μ¬μ¬μ© κ°λ₯ν JSON λμ½λλ₯Ό μμ±
μ§μ ν νμ μΌλ‘ λμ½λ©λ JSON κ°μ²΄μ κ°μ λ°ννλ λ©μλ
func decode<T>(
_ type: T.Type,
from data: Data
) throws -> T where T : Decodable
DecodingError.dataCorrupted(_:)
μλ¬λ₯Ό throwν¨