Last active
October 12, 2024 00:30
-
-
Save lucianoschillagi/8a659d076a23f77d00568b85dd2b257e to your computer and use it in GitHub Desktop.
json decoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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