flutter如何使用json_annotation
我在Flutter项目中想使用json_annotation来处理JSON序列化,但不太清楚具体步骤。请问:
- 需要添加哪些依赖项到pubspec.yaml?
- 如何创建模型类并使用注解?
- 代码生成命令应该怎么运行?
- 遇到"Could not generate fromJson"错误该如何解决? 希望能提供一个完整的配置示例,谢谢!
2 回复
在Flutter中使用json_annotation分四步:
- 添加依赖:
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
build_runner: ^2.4.4
json_serializable: ^6.7.1
- 创建模型类:
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);
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
- 生成代码:
flutter pub run build_runner build
- 使用:
// JSON转对象
Map<String, dynamic> json = {'name': '张三', 'age': 25};
User user = User.fromJson(json);
// 对象转JSON
Map<String, dynamic> userJson = user.toJson();
注意:修改模型后要重新运行build_runner。支持嵌套对象、自定义字段名等高级功能。
更多关于flutter如何使用json_annotation的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中使用json_annotation包可以实现JSON序列化和反序列化的自动化处理。以下是详细步骤:
1. 添加依赖
在 pubspec.yaml 中添加:
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
build_runner: ^2.4.4
json_serializable: ^6.7.1
2. 创建数据模型类
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart'; // 生成的文件
@JsonSerializable()
class User {
final String name;
final int age;
final String email;
User({
required this.name,
required this.age,
required this.email,
});
// 从JSON创建User实例
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
// 将User实例转换为JSON
Map<String, dynamic> toJson() => _$UserToJson(this);
}
3. 生成代码
运行以下命令生成序列化代码:
flutter pub run build_runner build
或监听文件变化自动生成:
flutter pub run build_runner watch
4. 使用示例
// JSON转对象
Map<String, dynamic> userJson = {
'name': '张三',
'age': 25,
'email': 'zhangsan@example.com'
};
User user = User.fromJson(userJson);
// 对象转JSON
Map<String, dynamic> json = user.toJson();
5. 高级配置
- 字段映射:使用
@JsonKey(name: 'user_name') - 忽略字段:使用
@JsonKey(ignore: true) - 默认值:使用
@JsonKey(defaultValue: 'unknown')
json_annotation大大简化了JSON处理,提高了开发效率。

