JSON 转 Dart 生成器

JSON 输入

正在加载编辑器…

生成的 Dart

Configuration

输入 JSON 数据以生成 Dart 类

具有空值安全和 JSON 序列化的类

如何将 JSON 转换为 Dart – 分步指南

使用此 JSON 转 Dart 生成器,可从 JSON 示例生成支持空安全的 Dart 类,适用于 Flutter 与 Dart 服务。

  1. 步骤 1 – 粘贴 JSON 示例

    • 将具有代表性的 JSON 对象或数组粘贴到左侧编辑器中。
    • 尽量包含嵌套对象、数组和可为 null 的字段,方便正确推断类型。
    • 使用 导入 从文件、URL 或示例数据加载 JSON。
  2. 步骤 2 – 选择 Dart 类选项

    • 为根模型设置 类名(例如 Root)。
    • 启用空安全并确认可选字段映射(例如 String?)。
    • 如使用代码生成,选择序列化风格(例如 json_serializable)。
  3. 步骤 3 – 检查生成的代码

    • 确认字段命名、类型推断,以及数组/对象的映射方式是否符合预期。
    • 根据需要调整 根类型名称、空值处理策略以及可选的框架选项。
    • 如果某些字段推断不准确,优化示例 JSON 后重新生成。
  4. 步骤 4 – 在 Flutter/Dart 中使用模型

    • 将生成类加入项目(例如放在 lib/models)。
    • 通过 fromJson 工厂方法或生成的序列化代码解析 JSON。
    • 运行 flutter format 以保持风格一致。
  5. 步骤 5 – 复制或下载

    • 将输出复制到项目中,或下载为文件。
    • 运行格式化/代码检查工具,让代码风格与项目保持一致。
    • 若目标语言需要序列化/解析库,请在项目中添加相应依赖。

快速提示

  • 使用嵌套类型来表达结构,避免模型过于臃肿。
  • 只有在 API 的时间格式稳定时才解析为 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 转 Dart 生成器配合使用的 JSON 与 Schema 工具。

常见问题

支持哪些 Dart 特性?

生成器创建具有适当类型安全的 Dart 类,支持手动 JSON 序列化和 json_annotation 包,对空值使用可空类型,并遵循 Dart 命名约定。

json_annotation 如何工作?

当选择 json_annotation 框架时,生成的类使用 @JsonSerializable() 注解,并使用 build_runner 自动生成 fromJson/toJson 方法。这提供了类型安全的 JSON 序列化。

可空值如何处理?

JSON 中的空值映射到 Dart 中的可空类型 (?),提供空值安全。必需字段在构造函数中使用 'required' 关键字,遵循 Dart 的空值安全原则。

Dart 的类型系统如何处理?

生成的 Dart 代码利用 Dart 的强类型系统,使用适当的类型(int、double、String、bool、List、Map),并遵循 Dart 约定如字段名的 camelCase。

JSON 转 Dart 生成器 | JSONSwiss