dart:convert
库 dart:convert(API 参考)包含 JSON 和 UTF-8 的转换器,当然也支持创建其他的转换器。JSON 是表示结构化对象和集合的一种简单的文本格式。UTF-8 是一种可表示 Unicode 字符集中所有字符的通用的可变宽度编码。
库 dart:convert 在 web 应用和命令行应用中均可使用。要使用它,导入 dart:convert。
import 'dart:convert';
解码和编码 JSON
在 Dart 中,使用 jsonEncode() 来解码一个 JSON 编码的字符串:
// 说明: 在 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() 编码一个受支持的对象为一个 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(只包含字符串的 key)是可以直接编码为 JSON 的。List 和 Map 对象被递归地编码。
你有两个选项来编码那些不被直接支持的对象。第一个是调用包含第二个参数的 encode()**:一个函数返回一个可被直接编码的对象。你的第二个选项是忽略第二个参数,这样编码器会调用对象的 **toJson() 方法。
要了解更多 JSON 相关的示例和链接,请参阅 JSON 支持。
解码和编码 UTF-8 字符
在 Dart 中,使用 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 = inputStream
.transform(utf8.decoder)
.transform(LineSplitter());
try {
await for (var line in lines) {
print('Got ${line.length} characters from stream');
}
print('file is now closed');
} catch (e) {
print(e);
}
使用 utf8.encode() 来编码一个 Dart 字符串为一个 UTF-8 编码的字节列表:
List<int> 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 参考。