Flutter JSON序列化插件json_serializable_generator的使用

json_serializable_generator

json_serializable_generator 提供了用于处理 JSON 的 Dart 构建系统构建器。此库会读取 .model.json 文件,并自动生成对应的 Dart 模型类文件(.model.dart)。

目前模型应该位于同一目录下,否则需要显式指定路径,如后文所述。


使用方法

简单情况

对于 int, double, bool, String, List, 和 Map 类型,该库依赖于默认的 Dart JSON 序列化。对于其他类型,则假定存在名为 fromJson(Map<String, dynamic> json) 的命名构造函数。

示例

{
  ...,
  "reference": "SomeGeneratedResource",
  "some_other_prop": "String"
}

复杂类型

以下是复杂类型的字段及其说明:

字段 是否必需 解释 默认值
type 类型名称(类名) -
readMethod 用于将 JSON 转换为类实例的方法(Function(String)),调用时传入 JSON 并返回类实例 命名构造函数或静态方法 fromJson
writeMethod 将类写入为字符串、整数、布尔值、映射或列表的方法 实例上的 toJson() 方法
importPath 结果模型类文件可以导入此类的路径。应为“绝对路径”。 回退到生成的 .model.dart 导入

示例

{
  ...,
  "externalResource": {
    "type": "ExternalResource",
    "writeMethod": "prettyWrite",
    "readMethod": "prettyRead",
    "importPath": "package:my_app/external_resources/ExternalResource.dart"
  }
}

构建配置 (build.yaml)

缓存模式(默认;不适用于 Flutter)

targets:
  $default:
    builders:
      json_serializable_generator:
        generate_for:
          include:
            - lib/**

源码模式(Flutter 必须使用)

targets:
  $default:
    builders:
      _generator:
        generate_for:
          include:
            - lib/**

builders:
  _generator:
    import: "package:json_serializable_generator/json_serializable_generator.dart"
    builder_factories:
      - "jsonSerializableGenerator"
    build_extensions: {".model.json": [".model.dart"]}
    auto_apply: root_package
    build_to: source

示例代码

以下是一个完整的示例,展示如何使用 json_serializable_generator 插件。

示例代码

example/main.dart

import 'dart:convert';
import 'dart:io';
import 'package:json_serializable_generator/json_serializable.dart'; // 引入插件
import './Example.model.dart'; // 引入生成的模型类

void main() {
  // 示例 JSON 数据
  String json = '''
  {
    "id": "abcdefg",
    "isRequired": true,
    "count": 42,
    "simpleSchema": {
      "id": 123456,
      "isRequired": false,
      "name": "Test Model Simple"
    },
    "someExternal": "some-id;string;false;123;",
    "anotherExternal": "another-id;string;false;123;",
    "someList": ["Adam", "Benjamin"],
    "someMapping": {
      "Adam": 1,
      "Benjamin": 2
    }
  }''';

  // 反序列化 JSON 数据
  Example deserializedModelInstance = JsonSerializable.fromJson<Example>(json);

  // 序列化模型数据为 JSON
  String serializedModelJson = jsonEncode(deserializedModelInstance.toJson());
  print(serializedModelJson);

  // 退出程序
  exit(0);
}

生成的模型类文件 (Example.model.dart)

// 自动生成的模型类
class Example {
  final String id;
  final bool isRequired;
  final int count;
  final SimpleSchema simpleSchema;
  final String someExternal;
  final String anotherExternal;
  final List<String> someList;
  final Map<String, int> someMapping;

  Example({
    required this.id,
    required this.isRequired,
    required this.count,
    required this.simpleSchema,
    required this.someExternal,
    required this.anotherExternal,
    required this.someList,
    required this.someMapping,
  });

  factory Example.fromJson(Map<String, dynamic> json) {
    return Example(
      id: json['id'],
      isRequired: json['isRequired'],
      count: json['count'],
      simpleSchema: SimpleSchema.fromJson(json['simpleSchema']),
      someExternal: json['someExternal'],
      anotherExternal: json['anotherExternal'],
      someList: List<String>.from(json['someList']),
      someMapping: Map<String, int>.from(json['someMapping']),
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'isRequired': isRequired,
        'count': count,
        'simpleSchema': simpleSchema.toJson(),
        'someExternal': someExternal,
        'anotherExternal': anotherExternal,
        'someList': someList,
        'someMapping': someMapping,
      };
}

// 内部模型类
class SimpleSchema {
  final int id;
  final bool isRequired;
  final String name;

  SimpleSchema({
    required this.id,
    required this.isRequired,
    required this.name,
  });

  factory SimpleSchema.fromJson(Map<String, dynamic> json) {
    return SimpleSchema(
      id: json['id'],
      isRequired: json['isRequired'],
      name: json['name'],
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'isRequired': isRequired,
        'name': name,
      };
}

更多关于Flutter JSON序列化插件json_serializable_generator的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


json_serializable 是一个用于 Flutter 和 Dart 的代码生成库,它可以帮助你自动生成 JSON 序列化和反序列化的代码。使用 json_serializable 可以避免手动编写繁琐的 fromJsontoJson 方法,从而提高开发效率。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 json_serializablebuild_runner 依赖。

dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.3.3
  json_serializable: ^6.6.1

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. 生成代码

在终端中运行以下命令来生成序列化代码:

flutter pub run build_runner build

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

4. 使用生成的代码

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

void main() {
  // JSON 字符串
  String jsonString = '{"name": "John Doe", "age": 30, "email": "john.doe@example.com"}';

  // 反序列化
  Map<String, dynamic> userMap = jsonDecode(jsonString);
  User user = User.fromJson(userMap);

  print('Name: ${user.name}, Age: ${user.age}, Email: ${user.email}');

  // 序列化
  Map<String, dynamic> userJson = user.toJson();
  print(jsonEncode(userJson));
}

5. 其他配置

@JsonSerializable 注解支持一些可选参数,可以用来定制序列化行为。例如:

@JsonSerializable(
  explicitToJson: true, // 嵌套对象的序列化
  fieldRename: FieldRename.snake, // 字段名转换为蛇形命名
  anyMap: true, // 允许 Map 中的键为任意类型
)
class User {
  // ...
}

6. 自动生成代码

如果你希望在每次保存文件时自动生成代码,可以使用以下命令:

flutter pub run build_runner watch

这将会监视你的文件变化,并在文件保存时自动生成代码。

7. 清理生成的文件

如果你想要清理生成的文件,可以运行以下命令:

flutter pub run build_runner clean
回到顶部