FlutterJsonToDart插件使用
1、在AndroidStudio的setting->plugins中查找FlutterJsonToDart并安装,让后重启AndroidStudio

2、选择mode需要存放的文件夹新建dart文件

3、在插件面板中写入需要序列化的json合文件名称

确认后会自动生成.dart和.g.dart文件

Json_serializable使用
1. 使用 @JsonKey 注解定制字段行为
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
@JsonKey(name: 'user_id') // JSON 中的 key 是 user_id,Dart 中是 userId
final int userId;
@JsonKey(includeIfNull: false) // 序列化时忽略 null 值
final String? nickname;
User(this.userId, this.nickname);
}
2. 使用 @JsonSerializable 的参数定制类级别行为
@JsonSerializable(
explicitToJson: true, // 子对象也使用 toJson
includeIfNull: false, // 整体不包含 null 字段
fieldRename: FieldRename.snake, // 自动将驼峰转为下划线命名
)
class MyModel { ... }
3. 手动编写 fromJson / toJson 并调用生成的方法(高级用法)
如果你有部分逻辑需要自定义,可以在你的 model 类中写自己的 fromJson,然后委托给生成的私有方法:
factory MyModel.fromJson(Map<String, dynamic> json) {
// 在这里做预处理
if (!json.containsKey('requiredField')) {
throw Exception('Missing required field');
}
return _$MyModelFromJson(json); // 调用生成的方法
}
Map<String, dynamic> toJson() => _$MyModelToJson(this);
4;@JsonKey(defaultValue: 'Guest')设置默认值
@JsonSerializable()
class User {
@JsonKey(defaultValue: 'Guest')
final String name; // 注意:这里声明为非空!
@JsonKey(defaultValue: 0)
final int age;
User({required this.name, required this.age});
factory User.fromJson(Map<String, dynamic> json) {
final cleanJson = Map<String, dynamic>.from(json)
..removeWhere((key, value) => value == null);
return _$UserFromJson(cleanJson);
}
Map<String, dynamic> toJson() => _$UserToJson(this);
}
注意: @JsonKey(includeIfNull: false) 只能保证序列化toJson时排除null值,如果反序列化fromJson时不会排除null值,这里需要重写方法
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
final String? name;
final int? age;
User({this.name, this.age});
// 自定义 fromJson:移除所有值为 null 的字段
factory User.fromJson(Map<String, dynamic> json) {
// 创建副本避免修改原始数据
final cleanJson = Map<String, dynamic>.from(json);
// 移除所有值为 null 的键
cleanJson.removeWhere((key, value) => value == null);
return _$UserFromJson(cleanJson);
}
Map<String, dynamic> toJson() => _$UserToJson(this);
}