美文网首页
flutter中序列化和反序列化,以及使用注解快速生成

flutter中序列化和反序列化,以及使用注解快速生成

作者: Poppy11 | 来源:发表于2023-12-17 14:18 被阅读0次

在 Flutter 中,序列化和反序列化是将对象转换为可传输或存储的格式(如 JSON)以及将可传输或存储的格式转换回对象的过程。

我认为最主要的是网络请求和响应

在与后端 API 进行通信时,常见的数据交换格式是 JSON。通过将对象序列化为 JSON,可以将数据发送到服务器,并在接收到响应后将其反序列化为对象。

1.首先引入以下三个包,可以使用注解,自动化序列化和反序列化,避免手动麻烦和拼写错误

dart pub add dev:json_serializable
dart pub add dev:build_runner
dart pub add json_annotation

2.例如我定义了Person类,注意此处必须得有part "xxxxx.dart"。

import 'package:json_annotation/json_annotation.dart';


part 'person.g.dart';

@JsonSerializable()
class Person {
  /// The generated code assumes these values exist in JSON.
  final String firstName, lastName;

  /// The generated code below handles if the corresponding JSON value doesn't
  /// exist or is empty.
  final DateTime? dateOfBirth;

  Person({required this.firstName, required this.lastName, this.dateOfBirth});

  /// Connect the generated [_$PersonFromJson] function to the `fromJson`
  /// factory.
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  /// Connect the generated [_$PersonToJson] function to the `toJson` method.
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

3. 运行命令生成序列化反序列化类

执行完命令后,你会看到生成了person.g.dart文件。

dart run build_runner build

相关文章

网友评论

      本文标题:flutter中序列化和反序列化,以及使用注解快速生成

      本文链接:https://www.haomeiwen.com/subject/cplogdtx.html