Skip to content

Instantly share code, notes, and snippets.

@lucianoschillagi
Last active October 12, 2024 00:30
Show Gist options
  • Save lucianoschillagi/8a659d076a23f77d00568b85dd2b257e to your computer and use it in GitHub Desktop.
Save lucianoschillagi/8a659d076a23f77d00568b85dd2b257e to your computer and use it in GitHub Desktop.
json decoder
import Foundation
// Converting JSON into data
let json = """
{
"name": "Dog",
"legs": 4
}
""".data(using: .utf8)!
struct Animal: Codable {
var name: String
var legs: Int
}
let decoder = JSONDecoder()
do {
// Converting data into a Swift object 'Animal' instance
let animal = try decoder.decode(Animal.self, from: json)
print(animal.name)
print(animal.legs)
} catch {
print("Error decoding JSON: \(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment