Flutter JSON注解生成插件flutter_annotation_json的使用

Flutter JSON注解生成插件flutter_annotation_json的使用

简介

flutter_annotation_json 是一个基于注解的 JSON 到模型转换工具,支持类型安全的 JSON 解析与生成。通过使用该插件,您可以轻松地将 JSON 数据映射到 Dart 对象,并自动生成解析方法。


示例代码

1. 定义模型类

首先,我们需要定义一个 Dart 类,并使用 @JsonObject() 注解来标记它。然后通过 part 关键字生成对应的 JSON 转换代码。

// 导入插件
import 'package:flutter_annotation_json/flutter_annotation_json.dart';

// 生成 JSON 转换代码
part 'user.json.dart';

// 使用 @JsonObject() 注解标记类
@JsonObject()
class UserInfo {
  // 定义字段
  final String name;
  final int age;
  final double height;
  final bool isVip;
  final DateTime lastLogin;
  final List<String> photos;
  final UserLevel level;
  final String? bio;
  final AddressInfo? addressInfo;

  // 构造函数
  UserInfo({
    required this.name,
    required this.age,
    required this.height,
    required this.isVip,
    required this.lastLogin,
    required this.photos,
    required this.level,
    this.bio,
    this.addressInfo,
    required this.session,
  });

  // 静态工厂方法,用于从 JSON 数据解析对象
  factory UserInfo.fromJson(Map<String, dynamic> json) => _$UserInfoFromJson(json);
}

// 定义嵌套的地址信息类
@JsonObject()
class AddressInfo {
  final String province;
  final String city;
  final String area;

  AddressInfo({
    required this.province,
    required this.city,
    required this.area,
  });

  // 静态工厂方法,用于从 JSON 数据解析对象
  factory AddressInfo.fromJson(Map<String, dynamic> json) => _$AddressInfoFromJson(json);
}

2. 使用枚举类型

如果需要使用枚举类型,可以通过 @JsonEnum() 注解来实现。以下是一个示例:

// 导入插件
import 'package:flutter_annotation_json/flutter_annotation_json.dart';

// 生成枚举类的 JSON 转换代码
part 'user.enum.dart';

// 定义枚举类型
@JsonEnum('vip')
enum UserLevel {
  @EnumValue('normal') // 映射为 "normal"
  normal,

  @EnumValue('vip') // 映射为 "vip"
  vip,

  @EnumValue('svip') // 映射为 "svip"
  svip,
}

// 扩展枚举类以获取其值
extension UserLevelValues on UserLevel {
  String get value => _$getValueForUserLevel(this); // 自动生成的方法
}

3. 自定义编码与解码

对于特殊类型的字段(如 Duration),可以使用自定义的编码和解码逻辑:

// 定义编码和解码函数
dynamic durationEncode(dynamic value) {
  return (value as Duration).inMilliseconds; // 将 Duration 转换为毫秒
}

Duration durationDecode(dynamic value) {
  return Duration(milliseconds: value); // 将毫秒转换回 Duration
}

// 在类中使用自定义编码和解码
@JsonField(encoder: durationEncode, decoder: durationDecode)
final Duration session;

自动生成代码

在完成上述代码后,需要运行以下命令来自动生成 JSON 转换代码:

flutter pub run build_runner build

生成的代码会出现在对应的 .json.dart.enum.dart 文件中。


测试 JSON 解析

以下是一个完整的 JSON 示例,展示如何解析 JSON 数据并生成对象:

void main() {
  // 原始 JSON 数据
  final jsonString = '''
  {
    "name": "Alice",
    "age": 25,
    "height": 1.68,
    "isVip": true,
    "lastLogin": "2023-10-01T12:00:00Z",
    "photos": ["photo1.jpg", "photo2.jpg"],
    "level": "vip",
    "bio": "A software engineer.",
    "addressInfo": {
      "province": "Beijing",
      "city": "Beijing",
      "area": "Haidian"
    },
    "session": 120000
  }
  ''';

  // 解析 JSON 数据
  final Map<String, dynamic> jsonMap = json.decode(jsonString);

  // 生成对象
  final userInfo = UserInfo.fromJson(jsonMap);

  // 输出结果
  print(userInfo);
}

更多关于Flutter JSON注解生成插件flutter_annotation_json的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter JSON注解生成插件flutter_annotation_json的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_annotation_json 是一个用于生成 JSON 序列化和反序列化代码的 Flutter 插件。它基于注解(annotation)的方式,通过生成代码来简化手动编写 JSON 转换逻辑的过程。以下是使用 flutter_annotation_json 的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 flutter_annotation_jsonbuild_runner 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_annotation_json: ^1.0.0  # 请使用最新版本

dev_dependencies:
  build_runner: ^2.1.0  # 用于生成代码

然后运行 flutter pub get 来获取依赖。

2. 创建模型类

创建一个 Dart 类,并使用 @JsonSerializable 注解标记该类。例如:

import 'package:flutter_annotation_json/flutter_annotation_json.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 反序列化
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  // 序列化为 JSON
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

3. 生成代码

使用 build_runner 生成 JSON 序列化和反序列化代码。在终端中运行以下命令:

flutter pub run build_runner build

这将生成一个名为 user.g.dart 的文件,其中包含 _$UserFromJson_$UserToJson 方法的实现。

4. 使用生成的代码

现在你可以使用生成的 fromJsontoJson 方法来序列化和反序列化 User 对象:

void main() {
  // JSON 数据
  Map<String, dynamic> json = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john.doe@example.com'
  };

  // 反序列化
  User user = User.fromJson(json);
  print('User: ${user.name}, ${user.age}, ${user.email}');

  // 序列化
  Map<String, dynamic> userJson = user.toJson();
  print('User JSON: $userJson');
}

5. 其他注解

flutter_annotation_json 还提供了一些其他注解来控制序列化和反序列化的行为,例如:

  • @JsonKey:用于指定 JSON 字段的名称或在序列化/反序列化时的行为。
  • @JsonSerializable:用于配置类的序列化行为。

例如:

@JsonSerializable()
class User {
  @JsonKey(name: 'full_name')
  final String name;

  @JsonKey(defaultValue: 18)
  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);
}

6. 清理生成的代码

如果你不再需要生成的代码,可以运行以下命令来清理:

flutter pub run build_runner clean
回到顶部