Created
November 25, 2024 13:41
-
-
Save lucianoschillagi/48a228e66c82d0293bb5f7195fa3a930 to your computer and use it in GitHub Desktop.
How to convert a JSON into a Swift object
This file contains hidden or 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() | |
// 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