The dart:convert Library

Learn the core capabilities of the Dart dart:convert library. The dart:convert library provides converters for JSON and UTF-8, and also supports custom converters.

JSON: A lightweight text format used to represent structured objects and collections.

UTF-8: A variable-width character encoding capable of representing all characters within the Unicode character set.

import 'dart:convert';Code language: JavaScript (javascript)

JSON Encoding and Decoding

jsonDecode(): JSON String → Dart Object

Decodes a JSON-formatted string into a Dart object.

Note: JSON strings must use double quotes " internally; single quotes ' are not allowed. This snippet is JSON, not Dart code.

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 Object → JSON String

Encodes serializable Dart objects into JSON strings:

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)

Types Natively Supported by JSON

Only the following types can be directly encoded to JSON:

int, double, String, bool, null, List, Map with String keys

Lists and Maps recursively encode all their inner elements.

UTF-8 Character Encoding & Decoding

utf8.decode(): UTF-8 Byte Array → Dart String

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)

Streaming UTF-8 Decoding (for files / network streams)

Use utf8.decoder together with Stream.transform(). Combine it with LineSplitter to read content line by line:

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(): String → UTF-8 Byte Array (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)

The dart:convert Library

Leave a Reply

Your email address will not be published. Required fields are marked *