JSON 和序列化
很难想象一个移动应用不需要在某个时候与 Web 服务器通信或轻松存储结构化数据。当制作网络连接应用时,它迟早需要使用一些旧的 JSON 数据。
本指南介绍了在 Flutter 中使用 JSON 的方法。它涵盖了在不同场景中使用哪种 JSON 解决方案以及原因。
哪种 JSON 序列化方法适合我?
#本文涵盖了两种处理 JSON 的通用策略
- 手动序列化
- 使用代码生成实现自动化序列化
不同的项目具有不同的复杂性和用例。对于较小的概念验证项目或快速原型,使用代码生成器可能过于繁琐。对于具有多个 JSON 模型且更复杂的应用程序,手动编码会很快变得乏味、重复,并容易产生许多小错误。
小型项目使用手动序列化
#手动 JSON 解码是指使用 dart:convert
中内置的 JSON 解码器。它涉及将原始 JSON 字符串传递给 jsonDecode()
函数,然后查找生成的 Map<String, dynamic>
中所需的值。它没有外部依赖或特定的设置过程,适用于快速概念验证。
当项目变大时,手动解码表现不佳。手动编写解码逻辑可能变得难以管理且容易出错。如果在访问不存在的 JSON 字段时出现拼写错误,您的代码将在运行时抛出错误。
如果您的项目中没有很多 JSON 模型,并且希望快速测试一个概念,手动序列化可能是您想要开始的方式。有关手动编码的示例,请参阅使用 dart:convert 手动序列化 JSON。
中大型项目使用代码生成
#使用代码生成进行 JSON 序列化意味着让外部库为您生成编码样板代码。经过一些初始设置后,您运行一个文件观察器,该观察器根据您的模型类生成代码。例如,json_serializable
和 built_value
就是这类库。
这种方法适用于大型项目。无需手动编写样板代码,访问 JSON 字段时的拼写错误会在编译时捕获。代码生成的缺点是需要一些初始设置。此外,生成的源文件可能会在项目导航器中产生视觉上的杂乱。
当您有一个中型或大型项目时,您可能希望使用生成的代码进行 JSON 序列化。要查看基于代码生成的 JSON 编码示例,请参阅使用代码生成库序列化 JSON。
Flutter 中是否有 GSON/Jackson/Moshi 等效项?
#简单的答案是没有。
这样的库需要使用运行时反射,这在 Flutter 中是被禁用的。运行时反射会干扰摇树优化,Dart 已经支持很长时间了。通过摇树优化,您可以从发布版本中“摇掉”未使用的代码。这显著优化了应用程序的大小。
由于反射默认使所有代码都隐式使用,因此它使摇树优化变得困难。工具无法知道哪些部分在运行时未使用,因此冗余代码很难剥离。使用反射时,应用程序大小无法轻易优化。
虽然您无法在 Flutter 中使用运行时反射,但有些库为您提供了同样易于使用的 API,但它们基于代码生成。此方法在代码生成库部分有更详细的介绍。
使用 dart:convert 手动序列化 JSON
#Flutter 中的基本 JSON 序列化非常简单。Flutter 有一个内置的 dart:convert
库,其中包含一个简单的 JSON 编码器和解码器。
以下示例 JSON 实现了一个简单的用户模型。
{
"name": "John Smith",
"email": "john@example.com"
}
使用 dart:convert
,您可以通过两种方式序列化此 JSON 模型。
内联序列化 JSON
#通过查看 dart:convert
文档,您会发现可以通过调用 jsonDecode()
函数来解码 JSON,并将 JSON 字符串作为方法参数。
final user = jsonDecode(jsonString) as Map<String, dynamic>;
print('Howdy, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');
不幸的是,jsonDecode()
返回一个 dynamic
,这意味着您在运行时之前不知道值的类型。使用这种方法,您会失去大多数静态类型语言特性:类型安全、自动补全以及最重要的是编译时异常。您的代码会立即变得更容易出错。
例如,每当您访问 name
或 email
字段时,您可能很快就会引入拼写错误。由于 JSON 存在于映射结构中,编译器不会知道这个拼写错误。
在模型类中序列化 JSON
#通过引入一个名为 User
的普通模型类来解决前面提到的问题。在 User
类中,您将找到
- 一个
User.fromJson()
构造函数,用于从映射结构构造新的User
实例。 - 一个
toJson()
方法,它将User
实例转换为映射。
使用这种方法,调用代码可以拥有类型安全、name
和 email
字段的自动补全以及编译时异常。如果您出现拼写错误或将字段视为 int
而不是 String
,应用程序将无法编译,而不是在运行时崩溃。
user.dart
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'] as String,
email = json['email'] as String;
Map<String, dynamic> toJson() => {'name': name, 'email': email};
}
解码逻辑的责任现在已转移到模型本身。使用这种新方法,您可以轻松解码用户。
final userMap = jsonDecode(jsonString) as Map<String, dynamic>;
final user = User.fromJson(userMap);
print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');
要编码用户,将 User
对象传递给 jsonEncode()
函数。您无需调用 toJson()
方法,因为 jsonEncode()
已为您完成。
String json = jsonEncode(user);
使用这种方法,调用代码根本不必担心 JSON 序列化。然而,模型类仍然需要。在生产应用中,您会希望确保序列化正常工作。实际上,User.fromJson()
和 User.toJson()
方法都需要进行单元测试以验证其正确行为。
然而,现实世界的场景并不总是那么简单。有时 JSON API 响应更为复杂,例如,它们包含必须通过自己的模型类解析的嵌套 JSON 对象。
如果有什么能为您处理 JSON 编码和解码,那会很棒。幸运的是,有!
使用代码生成库序列化 JSON
#尽管还有其他可用库,但本指南使用 json_serializable
,这是一个自动源代码生成器,可为您生成 JSON 序列化样板代码。
由于序列化代码不再是手动编写或维护的,因此您最大限度地降低了在运行时出现 JSON 序列化异常的风险。
在项目中设置 json_serializable
#要在项目中包含 json_serializable
,您需要一个常规依赖项和两个开发依赖项。简而言之,开发依赖项是未包含在我们的应用程序源代码中的依赖项——它们仅在开发环境中使用。
要添加依赖项,请运行 flutter pub add
flutter pub add json_annotation dev:build_runner dev:json_serializable
在您的项目根文件夹中运行 flutter pub get
(或在编辑器中单击 Packages get)以使这些新依赖项在您的项目中可用。
以 json_serializable 方式创建模型类
#以下展示了如何将 User
类转换为 json_serializable
类。为了简单起见,此代码使用前面示例中的简化 JSON 模型。
user.dart
import 'package:json_annotation/json_annotation.dart';
/// This allows the `User` class to access private members in
/// the generated file. The value for this is *.g.dart, where
/// the star denotes the source file name.
part 'user.g.dart';
/// An annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated.
@JsonSerializable()
class User {
User(this.name, this.email);
String name;
String email;
/// A necessary factory constructor for creating a new User instance
/// from a map. Pass the map to the generated `_$UserFromJson()` constructor.
/// The constructor is named after the source class, in this case, User.
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
/// `toJson` is the convention for a class to declare support for serialization
/// to JSON. The implementation simply calls the private, generated
/// helper method `_$UserToJson`.
Map<String, dynamic> toJson() => _$UserToJson(this);
}
通过此设置,源代码生成器会为从 JSON 编码和解码 name
和 email
字段生成代码。
如有必要,也可以轻松自定义命名策略。例如,如果 API 返回 snake_case 的对象,并且您希望在模型中使用 lowerCamelCase,则可以使用带有 name 参数的 @JsonKey
注解
/// Tell json_serializable that "registration_date_millis" should be
/// mapped to this property.
@JsonKey(name: 'registration_date_millis')
final int registrationDateMillis;
最好服务器和客户端遵循相同的命名策略。
@JsonSerializable()
提供了 fieldRename
枚举,用于将 dart 字段完全转换为 JSON 键。
修改 @JsonSerializable(fieldRename: FieldRename.snake)
等同于为每个字段添加 @JsonKey(name: '<snake_case>')
。
有时服务器数据不确定,因此需要在客户端验证和保护数据。
其他常用的 @JsonKey
注解包括
/// Tell json_serializable to use "defaultValue" if the JSON doesn't
/// contain this key or if the value is `null`.
@JsonKey(defaultValue: false)
final bool isAdult;
/// When `true` tell json_serializable that JSON must contain the key,
/// If the key doesn't exist, an exception is thrown.
@JsonKey(required: true)
final String id;
/// When `true` tell json_serializable that generated code should
/// ignore this field completely.
@JsonKey(ignore: true)
final String verificationCode;
运行代码生成实用程序
#首次创建 json_serializable
类时,您会遇到类似于以下内容的错误
Target of URI hasn't been generated: 'user.g.dart'.
这些错误完全正常,仅仅是因为模型类尚未生成代码。要解决此问题,请运行代码生成器,它会生成序列化样板代码。
有两种运行代码生成器的方法。
一次性代码生成
#通过在项目根目录中运行 dart run build_runner build --delete-conflicting-outputs
,您可以在需要时为模型生成 JSON 序列化代码。这将触发一次性构建,该构建会遍历源文件,选择相关文件,并为它们生成必要的序列化代码。
虽然这很方便,但如果您不必每次更改模型类时都手动运行构建,那就更好了。
持续生成代码
#一个 watcher 使我们的源代码生成过程更加方便。它会监视项目文件中的更改,并在需要时自动构建必要的文件。通过在项目根目录中运行 dart run build_runner watch --delete-conflicting-outputs
来启动 watcher。
启动一次监视器并让它在后台运行是安全的。
使用 json_serializable 模型
#要以 json_serializable
方式解码 JSON 字符串,您实际上不必对我们之前的代码进行任何更改。
final userMap = jsonDecode(jsonString) as Map<String, dynamic>;
final user = User.fromJson(userMap);
编码也是如此。调用 API 与之前相同。
String json = jsonEncode(user);
使用 json_serializable
,您可以忘记 User
类中的任何手动 JSON 序列化。源代码生成器创建一个名为 user.g.dart
的文件,其中包含所有必要的序列化逻辑。您不再需要编写自动化测试来确保序列化正常工作——现在由库负责确保序列化正常工作。
为嵌套类生成代码
#您的代码中可能存在类中嵌套类的情况。如果出现这种情况,并且您尝试以 JSON 格式将该类作为参数传递给服务(例如 Firebase),您可能会遇到 Invalid argument
错误。
考虑以下 Address
类
import 'package:json_annotation/json_annotation.dart';
part 'address.g.dart';
@JsonSerializable()
class Address {
String street;
String city;
Address(this.street, this.city);
factory Address.fromJson(Map<String, dynamic> json) =>
_$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
Address
类嵌套在 User
类中
import 'package:json_annotation/json_annotation.dart';
import 'address.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
User(this.name, this.address);
String name;
Address address;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
在终端中运行 dart run build_runner build --delete-conflicting-outputs
会创建 *.g.dart
文件,但私有的 _$UserToJson()
函数看起来像这样
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'name': instance.name,
'address': instance.address,
};
现在一切看起来都很好,但是如果你对 user 对象进行 print() 操作
Address address = Address('My st.', 'New York');
User user = User('John', address);
print(user.toJson());
结果是
{name: John, address: Instance of 'address'}
而您可能想要的是以下输出
{name: John, address: {street: My st., city: New York}}
要实现此功能,请在类声明上方的 @JsonSerializable()
注解中传递 explicitToJson: true
。现在 User
类如下所示
import 'package:json_annotation/json_annotation.dart';
import 'address.dart';
part 'user.g.dart';
@JsonSerializable(explicitToJson: true)
class User {
User(this.name, this.address);
String name;
Address address;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
有关更多信息,请参阅 JsonSerializable
类中 explicitToJson
的 json_annotation
包。
更多参考资料
#有关更多信息,请参阅以下资源
dart:convert
和JsonCodec
文档- pub.dev 上的
json_serializable
包 - GitHub 上的
json_serializable
示例 - 深入了解 Dart 的模式和记录 codelab
- 关于 如何在 Dart/Flutter 中解析 JSON 的终极指南