dart:convert
dart:convert 庫(API 參考)包含 JSON 和 UTF-8 的轉換器,並支援建立額外的轉換器。JSON 是一種簡單的文字格式,用於表示結構化物件和集合。UTF-8 是一種常見的變寬編碼,可以表示 Unicode 字元集中的所有字元。
要使用此庫,請匯入 dart:convert。
dart
import 'dart:convert';JSON 解碼與編碼
#使用 jsonDecode() 將 JSON 編碼的字串解碼為 Dart 物件
dart
// NOTE: Be sure to use double quotes ("),
// not single quotes ('), inside the JSON string.
// This string is JSON, not 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 格式的字串
dart
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() 將 UTF-8 編碼的位元組解碼為 Dart 字串
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() 方法
dart
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 字串編碼為 UTF-8 編碼位元組列表
dart
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 參考。