JSON 输入
生成的 Dart
输入 JSON 数据以生成 Dart 类
具有空值安全和 JSON 序列化的类
从 JSON 数据生成具有空值安全和 JSON 序列化的 Dart 类
输入 JSON 数据以生成 Dart 类
具有空值安全和 JSON 序列化的类
使用此 JSON 转 Dart 生成器,可从 JSON 示例生成支持空安全的 Dart 类,适用于 Flutter 与 Dart 服务。
步骤 1 – 粘贴 JSON 示例
导入 从文件、URL 或示例数据加载 JSON。步骤 2 – 选择 Dart 类选项
类名(例如 Root)。String?)。json_serializable)。步骤 3 – 检查生成的代码
根类型名称、空值处理策略以及可选的框架选项。步骤 4 – 在 Flutter/Dart 中使用模型
lib/models)。fromJson 工厂方法或生成的序列化代码解析 JSON。flutter format 以保持风格一致。步骤 5 – 复制或下载
快速提示
DateTime。// 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
}
// 生成的 Dart 模型(简化)
class Metadata {
final String plan;
const Metadata({required this.plan});
}
class Root {
final int id;
final String name;
final String? email;
final bool active;
final List<String> roles;
final Metadata metadata;
final String createdAt;
final double score;
final Object? notes;
const Root({
required this.id,
required this.name,
required this.email,
required this.active,
required this.roles,
required this.metadata,
required this.createdAt,
required this.score,
required this.notes,
});
}探索更多可与本 JSON 转 Dart 生成器配合使用的 JSON 与 Schema 工具。
生成器创建具有适当类型安全的 Dart 类,支持手动 JSON 序列化和 json_annotation 包,对空值使用可空类型,并遵循 Dart 命名约定。
当选择 json_annotation 框架时,生成的类使用 @JsonSerializable() 注解,并使用 build_runner 自动生成 fromJson/toJson 方法。这提供了类型安全的 JSON 序列化。
JSON 中的空值映射到 Dart 中的可空类型 (?),提供空值安全。必需字段在构造函数中使用 'required' 关键字,遵循 Dart 的空值安全原则。
生成的 Dart 代码利用 Dart 的强类型系统,使用适当的类型(int、double、String、bool、List、Map),并遵循 Dart 约定如字段名的 camelCase。