Tool Kumar 工具

JSON 转 Dart

为 Flutter API 响应生成 Dart 模型。每个嵌套类都有 final 字段、const 构造函数、fromJson 工厂构造函数和 toJson 方法。

如何使用这个工具

  1. 粘贴一份有代表性的响应,其中应包含字段存在差异的记录。
  2. 检查生成的输出,必要时修改根名称。
  3. 复制或下载代码,然后对照你的 API 契约检查类型。

示例演示

以下输出来自内置转换器。两个数组元素的 price 值用于推断浮点型字段;note 值分别为 null 和字符串,因此推断为可空字段。

输入

{
  "user-id": 42,
  "profile": {
    "city": "London",
    "created_at": "2026-10-14T09:00:00Z"
  },
  "items": [
    {
      "price": 12,
      "note": null
    },
    {
      "price": 12.5,
      "note": "gift"
    }
  ]
}

输出

class Root {
  final int userId;
  final Profile profile;
  final List<Item> items;

  const Root({
    required this.userId,
    required this.profile,
    required this.items,
  });

  factory Root.fromJson(Map<String, dynamic> json) => Root(
    userId: json['user-id'] as int,
    profile: Profile.fromJson(json['profile'] as Map<String, dynamic>),
    items: (json['items'] as List<dynamic>).map((e) => Item.fromJson(e as Map<String, dynamic>)).toList(),
  );

  Map<String, dynamic> toJson() => {
    'user-id': userId,
    'profile': profile.toJson(),
    'items': items.map((e) => e.toJson()).toList(),
  };
}

class Profile {
  final String city;
  final String createdAt;

  const Profile({
    required this.city,
    required this.createdAt,
  });

  factory Profile.fromJson(Map<String, dynamic> json) => Profile(
    city: json['city'] as String,
    createdAt: json['created_at'] as String,
  );

  Map<String, dynamic> toJson() => {
    'city': city,
    'created_at': createdAt,
  };
}

class Item {
  final double price;
  final String? note;

  const Item({
    required this.price,
    this.note,
  });

  factory Item.fromJson(Map<String, dynamic> json) => Item(
    price: (json['price'] as num).toDouble(),
    note: json['note'] as String?,
  );

  Map<String, dynamic> toJson() => {
    'price': price,
    'note': note,
  };
}

在 Flutter 中使用模型

导入 dart:convert,把生成的类粘贴到一个模型文件中。把解码后的响应 map 传给 Root.fromJson;jsonEncode 会调用生成的 toJson 方法。

如果你的项目已经在用 json_serializable,请把这些字段改写到那套流程中,而不是同时维护两套生成的 JSON 方法。

import 'dart:convert';

final model = Root.fromJson(jsonDecode(responseBody) as Map<String, dynamic>);
final text = jsonEncode(model.toJson());

选项与特殊情况

  • user-id 这样的 JSON 键会映射为 camelCase 字段,生成的 JSON 方法保留原始键名。
  • 整数和小数价格会合并为 double。解码器先转为 num 再调用 toDouble,所以两个示例值都能正常处理。
  • null 加字符串会生成 String?。只出现过 null 的字段保持为 dynamic,因为无法得知它本来的类型。
  • 日期保持为 String,DateTime 解析请自行检查。编译到 Web 的 Dart 无法精确表示所有大整数。

默认保护隐私

你的文档只保留在这个浏览器中。Tool Kumar 在你的设备上解析、转换并生成下载文件,无需账号,也没有上传步骤。

JSON 转 Dart:常见问题

会生成 json_serializable 注解吗?
不会。它直接写出 fromJson 和 toJson 方法,没有 @JsonSerializable 注解和 part 文件,也不需要 build_runner 步骤。
如何处理空安全?
值为 null 或在部分记录中缺失的字段,会被推断为可空。非空字段使用 required 构造函数参数。只出现过 null 的字段使用 dynamic。
能转换嵌套对象的数组吗?
能。示例会生成 List<Item>,解码时把每个输入元素交给 Item.fromJson,编码时对每个 item 调用 toJson。
需要 Flutter 包吗?
生成的模型只使用 Dart 核心类型。用 dart:convert 解码响应文本,再调用 Root.fromJson 即可。

相关工具

JSON 转 Swift 模型、JSON 转 Kotlin 数据类和JSON Schema 生成器。