dart:convert
dart:convert
库( API 参考 )包含 JSON 和 UTF-8 的转换器,以及创建其他转换器的支持。 JSON 是一种用于表示结构化对象和集合的简单文本格式。 UTF-8 是一种常见的变长编码,可以表示 Unicode 字符集中的每个字符。
要使用此库,请导入 dart:convert
。
import 'dart:convert';
JSON 的解码和编码
#使用 jsonDecode()
将 JSON 编码的字符串解码为 Dart 对象:
// 注意:请确保在 JSON 字符串中使用双引号 ("),而不是单引号 (')。
// 此字符串是 JSON,而不是 Dart。
var jsonString = '''
[
{"score": 40},
{"score": 80}
]
''';
var scores = jsonDecode(jsonString);
assert(scores is List);
var firstScore = scores[0];
assert(firstScore is Map);
assert(firstScore['score'] == 40);
使用 jsonEncode()
将支持的 Dart 对象编码为 JSON 格式的字符串:
var scores = [
{'score': 40},
{'score': 80},
{'score': 100, 'overtime': true, 'special_guest': null}
];
var jsonText = jsonEncode(scores);
assert(jsonText ==
'[{"score":40},{"score":80},'
'{"score":100,"overtime":true,'
'"special_guest":null}]');
只有 int
、 double
、 String
、 bool
、 null
、 List
或 Map
(带字符串键)类型的对象可以直接编码为 JSON。 List
和 Map
对象是递归编码的。
对于不能直接编码的对象,您有两种选择。第一种是使用第二个参数调用 jsonEncode()
:一个返回可以直接编码的对象的函数。您的第二个选择是省略第二个参数,在这种情况下,编码器会调用对象的 toJson()
方法。
有关更多示例和 JSON 相关包的链接,请参阅 使用 JSON 。
UTF-8 字符的解码和编码
#使用 utf8.decode()
将 UTF8 编码的字节解码为 Dart 字符串:
List<int> utf8Bytes = [
0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9,
0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3,
0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4,
0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5,
0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1
];
var funnyWord = utf8.decode(utf8Bytes);
assert(funnyWord == 'Îñţérñåţîöñåļîžåţîờñ');
要将 UTF-8 字符流转换为 Dart 字符串,请将 utf8.decoder
指定给 Stream 的 transform()
方法:
var lines = utf8.decoder.bind(inputStream).transform(const LineSplitter());
try {
await for (final line in lines) {
print('Got ${line.length} characters from stream');
}
print('file is now closed');
} catch (e) {
print(e);
}
使用 utf8.encode()
将 Dart 字符串编码为 UTF8 编码字节列表:
Uint8List encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');
assert(encoded.length == utf8Bytes.length);
for (int i = 0; i < encoded.length; i++) {
assert(encoded[i] == utf8Bytes[i]);
}
其他功能
#dart:convert
库还包含 ASCII 和 ISO-8859-1 (Latin1) 的转换器。有关详细信息,请参阅 dart:convert 库的 API 参考
除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.