dart:convert 函式庫

認識 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:

intdoubleStringboolnullList鍵為 String 的 Map

List、Map 會遞迴處理內部所有元素進行編碼。

UTF-8 字元編碼與解碼

utf8.decode():UTF-8 位元組陣列 → Dart 字串

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.decoderStream.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)

dart:convert 函式庫

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *