xxxxxxxxxx
import Foundation
// Define a struct representing the Swift model
struct MyModel: Codable {
let id: Int
let name: String
let email: String
}
// Sample JSON data
let json = """
{
"id": 123,
"name": "John Doe",
"email": "john.doe@example.com"
}
"""
// Convert JSON to Swift model object
do {
let jsonData = json.data(using: .utf8)!
let decoder = JSONDecoder()
let model = try decoder.decode(MyModel.self, from: jsonData)
// Access the model properties
print("ID: \(model.id)")
print("Name: \(model.name)")
print("Email: \(model.email)")
} catch {
print("Error: \(error)")
}
xxxxxxxxxx
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
}catch{ print("erroMsg") }
xxxxxxxxxx
struct MyStruct: Decodable {
let myProperty: String
// Add more properties as needed
}
let jsonString = """
{
"myProperty": "Hello, World!"
}
"""
let jsonData = jsonString.data(using: .utf8)!
do {
let decodedObject = try JSONDecoder().decode(MyStruct.self, from: jsonData)
print(decodedObject.myProperty) // Output: Hello, World!
} catch {
print("Error decoding JSON: \(error)")
}