dart:convert
dart:convert 函式庫(API 參考)具有 JSON 和 UTF-8 的轉換器,並支援建立額外的轉換器。JSON 是一種簡單的文字格式,用於表示結構化物件和集合。UTF-8 是一種常見的可變寬度編碼,可以表示 Unicode 字元集中的每個字元。
若要使用此函式庫,請匯入 dart:convert。
import 'dart:convert';
解碼和編碼 JSON
#使用 jsonDecode()
將 JSON 編碼的字串解碼為 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 格式的字串
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。頁面上次更新於 2024-11-17。 檢視原始碼 或 回報問題。