dart:convert

dart:convert

Dart의 dart:convert 라이브러리가 제공하는 주요 기능을 소개해 드릴게요. JSON과 UTF-8을 변환하는 도구들은 물론, 새 변환기를 직접 만들 수 있는 기반도 제공해요.

출처: dart:convert

본문

dart:convert 라이브러리(API 레퍼런스)에는 JSON과 UTF-8용 변환기(converter)가 있고, 새 변환기를 추가로 만들 수 있는 지원도 있어요. JSON은 구조화된 객체와 컬렉션을 표현하는 단순한 텍스트 형식이고, UTF-8은 Unicode 문자 집합의 모든 문자를 표현할 수 있는 흔한 가변 너비(variable-width) 인코딩이에요.

이 라이브러리를 사용하려면 dart:convert를 import 하세요.

import 'dart:convert';

JSON 디코딩과 인코딩 (Decoding and encoding 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으로 직접 인코딩할 수 있어요. ListMap 객체는 재귀적으로 인코딩돼요.

직접 인코딩할 수 없는 객체를 인코딩할 때는 두 가지 방법이 있어요. 첫 번째는 jsonEncode()에 두 번째 인자로 직접 인코딩 가능한 객체를 반환하는 함수를 넘기는 거예요. 두 번째 방법은 두 번째 인자를 생략하는 것인데, 이 경우 인코더가 그 객체의 toJson() 메서드를 호출해요.

더 많은 예시와 JSON 관련 패키지 링크는 Using JSON을 참고하세요.

UTF-8 문자 디코딩과 인코딩 (Decoding and encoding UTF-8 characters)

utf8.decode()로 UTF-8로 인코딩된 바이트를 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 문자열로 변환하려면, Streamtransform() 메서드에 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);
}

utf8.encode()로 Dart 문자열을 UTF-8 인코딩된 바이트 목록으로 인코딩할 수 있어요.

Uint8List encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');

assert(encoded.length == utf8Bytes.length);
for (int i = 0; i < encoded.length; i++) {
  assert(encoded[i] == utf8Bytes[i]);
}

기타 기능 (Other functionality)

dart:convert 라이브러리에는 ASCII와 ISO-8859-1(Latin1)용 변환기도 있어요. 자세한 내용은 dart:convert 라이브러리의 API 레퍼런스를 참고하세요.

더 알아보기