在flutter项目的pubspec.yaml文件中导入json_annotation库,在需要序列化的dart文件中使用@JsonSerializable注解类,然后在终端中运行命令"flutter pub run build_runner build"来生成对应的toJson方法。
示例代码:
dependencies: json_annotation: ^4.3.0
dev_dependencies: build_runner: ^2.1.4 json_serializable: ^4.1.3
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable() class User { String name; int age;
User(this.name, this.age);
factory User.fromJson(Map
Map
flutter pub run build_runner build
注意:如果使用的是VS Code编辑器,则可以通过左侧导航栏中的“Extensions”菜单安装Dart Data Class Generator插件,自动生成toJson和fromJson方法。