Flutter JSON序列化插件json_serializable_dart的使用
Flutter JSON序列化插件json_serializable_dart
的使用
使用说明
json_serializable_dart
是一个用于在 Dart 中实现 JSON 序列化的库。它可以帮助开发者轻松地将对象与 JSON 数据进行相互转换。
以下是一个简单的使用示例:
import 'package:json_serializable_dart/serializable_json.dart';
part 'json_seriazable_dart_example.g.dart'; // 自动生成的文件
void main() {
// 创建一个实例并从 JSON 初始化
final test = TestClass()..fromJson({'i': 1, 'm': 'ok'});
// 复制实例
final copy = TestClass()..copyFrom(test);
copy.g = ["I'm copy"]; // 修改复制实例的字段
// 打印原始和复制后的 JSON 数据
print(test.toMap()); // 输出原始数据
print(copy.toMap()); // 输出修改后的数据
}
// 定义带有序列化功能的类
[@SerializableJson](/user/SerializableJson)(methodOverlayName: 'Teradata', nullSafe: false)
class TestClass {
int? i; // 可选的整数字段
late String m; // 必须的字符串字段
List<String>? g; // 可选的字符串列表字段
// 将对象转换为 JSON 的方法
Map<String, dynamic> toMap() => _$TeradataToJson(this);
// 从 JSON 初始化对象的方法
void fromJson(Map<String, dynamic> json) {
_$TeradataFromJson(this, json);
}
// 示例:复制实例
void copyFrom(TestClass from) {
fromJson(from.toMap()); // 使用 fromJson 方法初始化当前实例
}
}
代码详解
-
导入库
import 'package:json_serializable_dart/serializable_json.dart';
导入
json_serializable_dart
库以启用 JSON 序列化功能。 -
生成器文件
part 'json_seriazable_dart_example.g.dart';
使用
part
指令声明自动生成的文件。此文件由工具生成,包含了序列化和反序列化的逻辑。 -
定义类及属性
[@SerializableJson](/user/SerializableJson)(methodOverlayName: 'Teradata', nullSafe: false) class TestClass { int? i; late String m; List<String>? g;
[@SerializableJson](/user/SerializableJson)
注解启用了序列化功能。methodOverlayName
参数指定了生成的方法名称前缀(例如_$TeradataToJson
和_$TeradataFromJson
)。nullSafe
参数设置为false
表示允许空值。
-
JSON 转换方法
Map<String, dynamic> toMap() => _$TeradataToJson(this); void fromJson(Map<String, dynamic> json) { _$TeradataFromJson(this, json); }
toMap()
方法将对象转换为 JSON 格式的Map
。fromJson()
方法将 JSON 数据解析为对象。
-
复制实例
void copyFrom(TestClass from) { fromJson(from.toMap()); }
提供了一个示例方法来复制实例。通过调用
fromJson()
方法,可以将另一个实例的数据复制到当前实例。
输出结果
运行上述代码后,控制台将输出以下内容:
{i: 1, m: ok}
{i: 1, m: ok, g: [I'm copy]}
更多关于Flutter JSON序列化插件json_serializable_dart的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter JSON序列化插件json_serializable_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
json_serializable
是一个用于自动生成 JSON 序列化和反序列化代码的 Flutter 插件。它可以帮助你减少手动编写样板代码的工作量,特别是在处理复杂的数据模型时。以下是使用 json_serializable
插件的步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 json_serializable
和 json_annotation
依赖。
dependencies:
flutter:
sdk: flutter
json_annotation: ^4.8.0
dev_dependencies:
build_runner: ^2.3.3
json_serializable: ^6.6.0
2. 创建数据模型类
接下来,创建一个数据模型类,并使用 @JsonSerializable
注解标记它。
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});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
3. 生成序列化代码
使用 build_runner
工具生成序列化和反序列化代码。在终端中运行以下命令:
flutter pub run build_runner build
这将会生成一个名为 user.g.dart
的文件,其中包含 _$UserFromJson
和 _$UserToJson
方法的实现。
4. 使用生成的代码
现在你可以使用生成的代码来序列化和反序列化 User
对象。
void main() {
// 反序列化
final jsonString = '{"name": "John", "age": 30, "email": "john@example.com"}';
final user = User.fromJson(jsonDecode(jsonString));
print(user.name); // 输出: John
// 序列化
final userJson = user.toJson();
print(jsonEncode(userJson)); // 输出: {"name":"John","age":30,"email":"john@example.com"}
}
5. 处理嵌套对象
如果你的数据模型包含嵌套对象,json_serializable
也可以处理。只需确保嵌套的类也使用 @JsonSerializable
注解。
@JsonSerializable()
class Address {
final String street;
final String city;
Address({required this.street, required this.city});
factory Address.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
@JsonSerializable()
class User {
final String name;
final int age;
final String email;
final Address address;
User({required this.name, required this.age, required this.email, required this.address});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
6. 处理可选字段
如果你的模型中有可选字段,可以使用 nullable
参数。
@JsonSerializable()
class User {
final String name;
final int? age; // 可选字段
User({required this.name, this.age});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
7. 自定义序列化
如果你需要对某些字段进行自定义序列化,可以使用 @JsonKey
注解。
@JsonSerializable()
class User {
final String name;
@JsonKey(name: 'user_age')
final int age;
User({required this.name, required this.age});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
8. 清理生成的文件
如果你不再需要生成的文件,可以运行以下命令来清理它们:
flutter pub run build_runner clean