Dart dart:convert 라이브러리의 핵심 기능을 알아봅니다. dart:convert 라이브러리는 JSON, UTF-8 변환기를 제공하며 사용자 정의 변환기도 지원합니다.
JSON: 구조화된 객체와 컬렉션을 표현하기 위한 간결한 텍스트 형식입니다.
UTF-8: 가변 길이 인코딩 방식으로, 유니코드 문자 집합의 모든 문자를 표현할 수 있습니다.
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으로 직접 인코딩할 수 있습니다.
int, double, String, bool, null, List, 키가 String인 Map
List와 Map은 내부 요소를 재귀적으로 인코딩합니다.
UTF-8 문자 인코딩 및 디코딩
utf8.decode(): UTF-8 바이트 배열 → 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)
스트리밍 UTF-8 디코딩 (파일 / 네트워크 스트림 처리)
utf8.decoder 와 Stream.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 라이브러리