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 中是被禁用的。运行时反射会干扰 摇树优化(tree shaking),而 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
,你需要一个常规依赖项和两个开发依赖项(dev dependencies)。简而言之,开发依赖项是不包含在应用程序源代码中的依赖项——它们仅在开发环境中使用。
要添加依赖项,运行 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
来启动观察器。
启动观察器一次并让其在后台运行是安全的。
使用 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,
};
现在看起来一切正常,但如果你对用户对象执行 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);
}
有关更多信息,请参阅 json_annotation
软件包中 JsonSerializable
类里的 explicitToJson
。
更多参考
#有关更多信息,请参阅以下资源
dart:convert
和JsonCodec
文档- pub.dev 上的
json_serializable
软件包 - GitHub 上的
json_serializable
示例 - 《深入了解 Dart 的模式和记录》Codelab
- 这篇关于如何在 Dart/Flutter 中解析 JSON 的终极指南