Flutter JSON序列化与反序列化插件json_serializable_converters的使用
Flutter JSON序列化与反序列化插件json_serializable_converters
的使用
特性
JsonSerializable
converters for core dart classes 提供了对 Dart 核心类的支持。
特性
- 完全覆盖测试
- 集成简单
支持的类型
Bytes
(Uint8List
,List<int>
),以 base64 序列化DateTime
Directory
File
Duration
- 通用枚举 (
Generic Enums
) Uri
所有转换器还支持一个 nullable()
静态方法,用于获取该转换器的可空版本。
使用方式
以下是一个完整的示例,展示如何使用 json_serializable_converters
插件进行 JSON 的序列化与反序列化。
// 导入必要的库
import 'dart:io'; // 用于处理文件和目录
import 'package:json_annotation/json_annotation.dart'; // 主要的 JSON 转换库
import 'package:json_serializable_converters/json_serializable_converters.dart'; // 自定义转换器
// 生成的代码文件
part 'json_serializable_converters_example.g.dart';
// 定义枚举类型
enum TestEnum { value1, value2 }
// 使用 [@JsonSerializable](/user/JsonSerializable) 注解并指定自定义转换器
[@JsonSerializable](/user/JsonSerializable)(
converters: [
BytesConverter(), // 转换 Uint8List 或 List<int>
DateTimeConverter(), // 转换 DateTime
DurationConverter(), // 转换 Duration
UriConverter(), // 转换 Uri
FileConverter(), // 转换 File
DirectoryConverter(), // 转换 Directory
EnumConverter(TestEnum.values), // 转换枚举
],
)
class Model {
final DateTime dateTime; // 时间戳
final Duration duration; // 持续时间
final Uri uri; // URI 地址
final List<int> bytes; // 字节数组
final File file; // 文件对象
final Directory directory; // 目录对象
final TestEnum enumValue; // 枚举值
// 构造函数
Model(this.dateTime, this.duration, this.uri, this.bytes, this.file, this.directory, this.enumValue);
// 反序列化方法
factory Model.fromJson(Map<String, dynamic> json) => _$ModelFromJson(json);
// 序列化方法
Map<String, dynamic> toJson() => _$ModelToJson(this);
}
void main() {
// 创建一个示例对象
final model = Model(
DateTime.now(), // 当前时间
const Duration(seconds: 10), // 10 秒
Uri.parse('https://example.com'), // 示例 URI
[1, 2, 3], // 示例字节数组
File('example.txt'), // 示例文件
Directory('example_dir'), // 示例目录
TestEnum.value1, // 示例枚举
);
// 将对象转换为 JSON
final jsonString = model.toJson();
print('JSON 输出: $jsonString');
// 将 JSON 转换回对象
final parsedModel = Model.fromJson(jsonString);
print('解析后的对象: $parsedModel');
}
更多关于Flutter JSON序列化与反序列化插件json_serializable_converters的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter JSON序列化与反序列化插件json_serializable_converters的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
json_serializable
是 Flutter 中一个非常流行的 JSON 序列化与反序列化插件,它可以帮助开发者自动生成将 Dart 对象转换为 JSON 以及从 JSON 转换为 Dart 对象的代码。json_serializable_converters
是 json_serializable
的一个扩展,它提供了一些额外的转换器,用于处理一些特殊的数据类型或格式。
1. 安装依赖
首先,你需要在 pubspec.yaml
文件中添加 json_serializable
和 json_serializable_converters
的依赖:
dependencies:
flutter:
sdk: flutter
json_annotation: ^4.8.1
dev_dependencies:
build_runner: ^2.3.3
json_serializable: ^6.6.1
json_serializable_converters: ^1.0.0
2. 创建数据模型
接下来,创建一个 Dart 类来表示你的数据模型。例如,假设你有一个 User
类:
import 'package:json_annotation/json_annotation.dart';
import 'package:json_serializable_converters/json_serializable_converters.dart';
part 'user.g.dart';
[@JsonSerializable](/user/JsonSerializable)()
class User {
final String name;
final int age;
@JsonKey(name: 'created_at')
@DateTimeConverter()
final DateTime createdAt;
User({required this.name, required this.age, required this.createdAt});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
在这个例子中,User
类有三个字段:name
、age
和 createdAt
。createdAt
字段使用了 DateTimeConverter
,这是 json_serializable_converters
提供的一个转换器,用于将 DateTime
对象与 JSON 字符串之间进行转换。
3. 生成代码
运行以下命令来生成序列化和反序列化的代码:
flutter pub run build_runner build
这将会生成一个 user.g.dart
文件,其中包含了 _$UserFromJson
和 _$UserToJson
方法的实现。
4. 使用生成的代码
现在你可以使用生成的代码来序列化和反序列化 User
对象:
void main() {
final user = User(name: 'John Doe', age: 30, createdAt: DateTime.now());
// 序列化为 JSON
final userJson = user.toJson();
print(userJson);
// 反序列化为 Dart 对象
final userFromJson = User.fromJson(userJson);
print(userFromJson);
}
5. 其他转换器
json_serializable_converters
还提供了其他一些常用的转换器,例如:
BigIntConverter
: 用于处理BigInt
类型。DurationConverter
: 用于处理Duration
类型。UriConverter
: 用于处理Uri
类型。
你可以根据需要选择合适的转换器来使用。
6. 自定义转换器
如果你有特殊的需求,也可以自定义转换器。只需要实现 JsonConverter
接口即可:
class CustomConverter implements JsonConverter<CustomType, String> {
const CustomConverter();
@override
CustomType fromJson(String json) {
// 实现从 JSON 到 CustomType 的转换
}
@override
String toJson(CustomType object) {
// 实现从 CustomType 到 JSON 的转换
}
}
然后在你的数据模型中使用这个自定义转换器:
[@JsonSerializable](/user/JsonSerializable)()
class MyModel {
[@CustomConverter](/user/CustomConverter)()
final CustomType customField;
MyModel({required this.customField});
factory MyModel.fromJson(Map<String, dynamic> json) => _$MyModelFromJson(json);
Map<String, dynamic> toJson() => _$MyModelToJson(this);
}