许多移动或网页应用都使用 JSON 来处理类似与服务器交换数据的任务。本文将讨论如果使用 Dart 对 JSON 数据进行序列化和反序列化:即 Dart 对象与 JSON 数据之间的相互转换。
Most mobile and web apps use JSON for tasks such as exchanging data with a web server. This page discusses Dart support for JSON serialization and deserialization: converting Dart objects to and from JSON.
需要用到的库
Libraries
下述的库和包可以用作于所有的 Dart 平台:
The following libraries and packages are useful across Dart platforms:
-
dart:convert
包含 JSON 数据和 UTF-8(JSON 数据需要的字符编码)的转换器。dart:convert
Converters for both JSON and UTF-8 (the character encoding that JSON requires). -
package:json_serializable
一个易于使用的代码生成包。当你添加一些元注解以及使用该包提供的构建器时, Dart 编译器可以为你生成序列化和反序列化的代码。package:json_serializable
An easy-to-use code generation package. When you add some metadata annotations and use the builder provided by this package, the Dart build system generates serialization and deserialization code for you. -
package:built_value
一个强大的,可以作为 json_serializable 替代的 package。package:built_value
A powerful, opinionated alternative to json_serializable.
相关的 Flutter 资源
Flutter resources
JSON 和序列化
向你展示 Flutter 应用是如何使用 dart:convert 和
json_serializable 进行序列化和反序列化的。
JSON and serialization
Shows how Flutter apps can serialize and deserialize both
with dart:convert and with json_serializable.
相关的 Web 应用资源
Web app resources
通过 HttpRequest 使用 HTTP 资源
向你演示如何使用 HttpRequest 与服务器交换数据。该资源是 dart:html 库概览 的一部分。
Using HTTP resources with HttpRequest
Demonstrates how to use HttpRequest to exchange data with a web server.
Part of the dart:html library tour.