了解 Dart dart:convert 库的核心功能。 dart:convert 库提供 JSON、UTF-8 转换器,同时支持自定义转换器。
JSON:用于表达结构化对象与集合的简易文本格式。
UTF-8:可变宽度编码,可表示 Unicode 字符集内所有字符。
import 'dart:convert';Code language: JavaScript (javascript)
JSON 编解码
jsonDecode ():JSON 字符串 → Dart 对象
将 JSON 格式字符串解码为 Dart 对象。
注意:JSON 字符串内部必须使用双引号
",不能使用单引号';这段文本是 JSON,不是 Dart 代码。
import 'dart:convert';
void main() {
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);
}Code language: Dart (dart)
jsonEncode ():Dart 对象 → JSON 字符串
将可序列化 Dart 对象编码为 JSON 字符串:
import 'dart:convert';
void main() {
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}]',
);
}Code language: Dart (dart)
JSON 直接支持的类型
只有以下类型可以直接编码为 JSON:
int、double、String、bool、null、List、键为 String 的 Map
List、Map 会递归编码内部元素。
UTF-8 字符编解码
utf8.decode ():UTF-8 字节数组 → Dart String
import 'dart:convert';
void main() {
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ñåţîöñåļîžåţîờñ');
}Code language: Dart (dart)
流式 UTF-8 解码(处理文件 / 网络流)
使用 utf8.decoder 配合 Stream.transform(),配合 LineSplitter 按行读取:
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);
}Code language: Dart (dart)
utf8.encode ():字符串 → UTF-8 字节数组(Uint8List)
Uint8List encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');
assert(encoded.length == utf8Bytes.length);
for (int i = 0; i < encoded.length; i++) {
assert(encoded[i] == utf8Bytes[i]);
}Code language: Dart (dart)
Previous: dart:math 库
Next: dart:core 核心库