How do I encode a struct using JSON with Swift?

import Foundation // Define the struct struct Person: Codable { var name: String var age: Int var email: String } // Create an instance of the struct let person = Person(name: "John Doe", age: 30, email: "john.doe@example.com") // Encode the struct to JSON do { let jsonData = try JSONEncoder().encode(person) let jsonString = String(data: jsonData, encoding: .utf8) print(jsonString ?? "Failed to encode JSON") } catch { print("Error encoding JSON: \(error)") }

Swift JSON Codable