중급
JSON serialization
서버에서 받은 JSON을 안전한 Dart 모델로 변환합니다.
핵심 개념
JSON serialization 주요 항목
왜 모델 변환이 필요한가
JSON은 런타임 데이터이기 때문에 타입 오류가 뒤늦게 발견될 수 있습니다.
언제 쓰나: fromJson과 toJson을 사용하면 서버 데이터와 앱 내부 모델의 경계를 명확히 할 수 있습니다.
Flutter에서: 큰 프로젝트에서는 코드 생성 도구를 사용해 반복적인 변환 코드를 줄일 수 있습니다.
class Lesson {
const Lesson({required this.title});
final String title;
factory Lesson.fromJson(Map<String, dynamic> json) {
return Lesson(title: json['title'] as String? ?? '제목 없음');
}
}
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color(0xFFDCE6EF)),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: const Color(0xFFEEF7FB),
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'제목 없음',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900),
),
)
],
),
)
제목 없음
주의점
서버 값이 없거나 타입이 달라질 수 있으므로 nullable과 기본값을 신중히 설계합니다.
언제 쓰나: API 응답을 화면 코드에서 직접 Map으로 읽으면 테스트와 유지보수가 어려워집니다.
Flutter에서: 모델 변환은 data layer에 두고 UI는 모델 타입만 사용하게 만드는 편이 좋습니다.
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text('주의점', style: TextStyle(fontWeight: FontWeight.bold)),
SizedBox(height: 8),
Text('서버 값이 없거나 타입이 달라질 수 있으므로 nullable과 기본값을 신중히 설계합니다.'),
],
),
),
)
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color(0xFFDCE6EF)),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: const Color(0xFFEEF7FB),
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'주의점',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900),
),
)
],
),
)
주의점
확장 개념
수동 직렬화와 코드 생성
- 작은 모델은 factory fromJson과 toJson을 직접 작성해도 충분합니다.
- 필드가 많거나 모델이 자주 바뀌는 프로젝트는 json_serializable 같은 코드 생성 도구가 실수를 줄여 줍니다.
- 서버 응답의 null, 누락 필드, 타입 불일치 상황을 모델 변환 단계에서 처리해야 합니다.
코드
예제
factory Lesson.fromJson(Map<String, dynamic> json) {
return Lesson(
title: json['title'] as String? ?? '제목 없음',
);
}
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color(0xFFDCE6EF)),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: const Color(0xFFEEF7FB),
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'제목 없음',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900),
),
)
],
),
)
제목 없음
다음 단계
실습 체크리스트
fromJson 작성toJson 작성nullable 필드 처리모델과 UI 분리
- 출처세부 기준과 최신 변경 사항을 확인할 수 있습니다.
- Flutter API Reference클래스, 메서드, 생성자 세부 정의를 확인합니다.
- Data & backend네트워크, 저장소, 직렬화, Firebase 문서를 함께 봅니다.