dart:convert
dart:convert ライブラリ(APIリファレンス)には、JSONおよびUTF-8用のコンバーターと、追加のコンバーターを作成するためのサポートが含まれています。JSON は、構造化されたオブジェクトやコレクションを表現するためのシンプルなテキストフォーマットです。UTF-8 は、Unicode文字セットのすべての文字を表現できる、一般的な可変幅エンコーディングです。
このライブラリを使用するには、dart:convert をインポートします。
import 'dart:convert';JSONのデコードとエンコード
#JSONエンコードされた文字列を `jsonDecode()` を使用して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);サポートされているDartオブジェクトを `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(文字列キーを持つ)の型のオブジェクトのみが、直接JSONにエンコード可能です。ListおよびMapオブジェクトは再帰的にエンコードされます。
直接エンコードできないオブジェクトをエンコードするには、2つのオプションがあります。1つ目は、2番目の引数として直接エンコード可能なオブジェクトを返す関数を指定して `jsonEncode()` を呼び出すことです。2つ目のオプションは、2番目の引数を省略することで、エンコーダーがオブジェクトの `toJson()` メソッドを呼び出します。
その他の例やJSON関連パッケージへのリンクについては、JSONの使用 を参照してください。
UTF-8文字のデコードとエンコード
#UTF8エンコードされたバイトをDart文字列にデコードするには `utf8.decode()` を使用します
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文字列に変換するには、Streamの `transform()` メソッドに `utf8.decoder` を指定します
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);
}Dart文字列をUTF8エンコードされたバイトのリストとしてエンコードするには `utf8.encode()` を使用します
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リファレンス を参照してください。