将 JSON 转换为 Dart class!

输入 JSON,即可生成包含嵌套对象的 Dart class 代码!支持 Flutter, fromJson, toJson。
JSON
结果
 

将 JSON 转换为 Dart class!

把 JSON 转换成带有 fromJson 工厂构造函数和 toJson 方法的 Dart 类。生成的是不依赖任何代码生成包的纯 Dart 代码,所以没有 build_runner 这一步。

适合那些把 http 或 dio 返回的原始 Map<String, dynamic> 直接传给 widget、想换成正经模型类的 Flutter 应用,也适合在引入 json_serializable 之前就需要可用序列化的小项目。

使用方法

  1. 粘贴要转换的 JSON。
  2. 在 类型名 中输入顶层类的名称(例如 Store)。
  3. 把输出粘贴到 lib/models/ 下的文件中,无需任何 import。
  4. 用 Store.fromJson(jsonDecode(response.body) as Map<String, dynamic>) 创建对象,用 jsonEncode(store.toJson()) 发送。

示例

输入 (JSON)
{
  "storeId": 77,
  "storeName": "Mapo Kimbap",
  "isOpen": true,
  "rating": 4.7,
  "menuItems": [
    { "name": "Tuna Kimbap", "price": 4500, "soldOut": false },
    { "name": "Ramyeon", "price": 5000, "soldOut": true, "spicy": 2 }
  ]
}
输出 (Dart)
class Store {
  final int storeId;
  final String storeName;
  final bool isOpen;
  final double rating;
  final List<MenuItem> menuItems;

  Store({
    required this.storeId,
    required this.storeName,
    required this.isOpen,
    required this.rating,
    required this.menuItems,
  });

  factory Store.fromJson(Map<String, dynamic> json) => Store(
        storeId: json['storeId'] as int,
        storeName: json['storeName'] as String,
        isOpen: json['isOpen'] as bool,
        rating: (json['rating'] as num).toDouble(),
        menuItems: (json['menuItems'] as List<dynamic>).map((e) => MenuItem.fromJson(e as Map<String, dynamic>)).toList(),
      );

  Map<String, dynamic> toJson() => {
        'storeId': storeId,
        'storeName': storeName,
        'isOpen': isOpen,
        'rating': rating,
        'menuItems': menuItems.map((e) => e.toJson()).toList(),
      };
}

class MenuItem {
  final String name;
  final int price;
  final bool soldOut;
  final int? spicy;

  MenuItem({
    required this.name,
    required this.price,
    required this.soldOut,
    this.spicy,
  });

  factory MenuItem.fromJson(Map<String, dynamic> json) => MenuItem(
        name: json['name'] as String,
        price: json['price'] as int,
        soldOut: json['soldOut'] as bool,
        spicy: json['spicy'] as int?,
      );

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

menuItems 数组的元素变成了 MenuItem 类,在 fromJson 中通过 .map(...).toList() 转换。rating 以 (json['rating'] as num).toDouble() 读取,即使值是整数也安全;只在部分菜品中出现的 spicy 是 int?,在构造函数中不带 required。

支持的功能

  • 所有字段都是 final;构造函数使用命名参数({required this.x})。
  • 手写风格的 factory X.fromJson(Map<String, dynamic> json) 和 Map<String, dynamic> toJson(),不依赖任何包。
  • 嵌套对象和对象数组会调用子类的 fromJson / toJson。
  • double 字段通过 (as num).toDouble() 读取,因此 4 这样的 JSON 整数不会抛出类型转换错误。
  • 在部分元素中缺失或包含 null 的字段变成可空类型(int?),并在 fromJson 中原样传递 null。
  • 混合类型的值为 dynamic;class、is 等 Dart 保留字会加上后缀下划线。
  • 顶层为数组时生成 typedef Root = List<RootItem>;。

使用场景

Flutter 页面的 API 模型

在 FutureBuilder 或 Riverpod/Bloc 的状态中传递 Map,key 拼错要到运行时才会发现。有了生成的类,store.menuItems.first.price 就有补全和类型检查。

本地缓存

把 jsonEncode(store.toJson()) 存进 shared_preferences 或文件,启动时用 fromJson 恢复,几行代码就能实现缓存。

引入 json_serializable 之前的草稿

先确定字段列表和类型;随着项目变大,再给同样的字段加上 @JsonSerializable(),迁移到代码生成。

注意事项与限制

  • 类型是用浏览器的 JSON 解析器推断的,它会把 5000.0 读成整数 5000。而 Dart 的 jsonDecode 会把 5000.0 保留为 double,于是 as int 会抛出异常。价格、坐标等可能带小数点的字段请改为 double。
  • 即使可空字段为 null,toJson 也会写出它('spicy': null)。如果服务器拒绝 null key,请有条件地省略。
  • 日期字符串保持为 String;请自行用 DateTime.parse(json['createdAt'] as String) 转换。
  • 不会生成 copyWith、==/hashCode 或 toString。如果需要,可以考虑 freezed 或 equatable。
  • dynamic 字段存放的值不经检查;知道真实类型后请替换掉。

常见问题

能生成 json_serializable 或 freezed 的代码吗?

输出是不依赖包的手写风格 fromJson/toJson。保留字段声明,加上 @JsonSerializable() 和 part 'store.g.dart';,再运行 dart run build_runner build,就能切换到代码生成。

出现了 type 'int' is not a subtype of type 'double'。

当代码用 as double 转换而 JSON 中的值是整数时就会出现这个错误。生成的 double 字段使用 (as num).toDouble() 来避免它;手动修改过的字段也请采用同样的写法。

怎样解码列表响应([ {...}, {...} ])?

顶层为数组时会生成一个 typedef 和元素类。对每个元素调用 fromJson:(jsonDecode(body) as List<dynamic>).map((e) => RootItem.fromJson(e as Map<String, dynamic>)).toList()。

在没有空安全的旧项目中能用吗?

输出使用 Dart 2.12 起的健全空安全语法(int?、required)。空安全之前的项目需要去掉 ? 和 required 才能编译。