Skip to content

Instantly share code, notes, and snippets.

@lucianoschillagi
Created November 25, 2024 13:41
Show Gist options
  • Save lucianoschillagi/48a228e66c82d0293bb5f7195fa3a930 to your computer and use it in GitHub Desktop.
Save lucianoschillagi/48a228e66c82d0293bb5f7195fa3a930 to your computer and use it in GitHub Desktop.
How to convert a JSON into a Swift object
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()
// Converting data into a Swift object 'Animal' instance
do {
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