JSON 输入
生成的 Swift
输入 JSON 数据以生成 Swift 结构体
具有 Codable 支持和类型安全的结构体
从 JSON 数据生成具有 Codable 支持的 Swift 结构体
输入 JSON 数据以生成 Swift 结构体
具有 Codable 支持和类型安全的结构体
使用此 JSON 转 Swift 生成器,可从 JSON 示例生成 Codable Swift struct,适用于 iOS/macOS 与 Swift 服务。
步骤 1 – 粘贴 JSON 示例
导入 从文件、URL 或示例数据加载 JSON。步骤 2 – 选择 Swift struct 选项
结构体名称(例如 Root)。String? 等可空类型。步骤 3 – 检查生成的代码
根类型名称、空值处理策略以及可选的框架选项。步骤 4 – 使用 Codable 解析 JSON
Codable。JSONDecoder 将 JSON 解码为根结构体。CodingKeys 或日期解码策略。步骤 5 – 复制或下载
快速提示
JSONDecoder.dateDecodingStrategy 配合 ISO8601。CodingKeys 或 keyDecodingStrategy。// JSON 输入
{
"id": 123,
"name": "Maeve Winters",
"email": "[email protected]",
"active": true,
"roles": ["admin", "editor"],
"metadata": { "plan": "pro" },
"createdAt": "2024-03-01T10:15:00Z",
"score": 99.5,
"notes": null
}
// 生成的 Swift 模型(简化)
struct Metadata: Codable {
let plan: String
}
struct Root: Codable {
let id: Int
let name: String
let email: String?
let active: Bool
let roles: [String]
let metadata: Metadata
let createdAt: String
let score: Double
let notes: String?
}探索更多可与本 JSON 转 Swift 生成器配合使用的 JSON 与 Schema 工具。
生成器创建具有适当类型安全的 Swift 结构体,支持 Codable 协议进行 JSON 序列化/反序列化,对空值使用可选类型,并遵循 Swift 命名约定。
当选择 Codable 框架时,生成的结构体自动符合 Codable 协议,使用 JSONEncoder 和 JSONDecoder 实现无缝 JSON 编码/解码。
JSON 中的空值映射到 Swift 中的可选类型 (?),提供类型安全性并需要显式解包,遵循 Swift 的空值安全方法。
生成的 Swift 代码利用 Swift 的强类型系统,使用适当的类型(Int、Double、String、Bool、[Any]、[String: Any]),并使用结构体进行不可变数据模型的值语义。