JSON을 fromJson 팩토리와 toJson 메서드가 들어 있는 Dart 클래스로 바꿉니다. 코드 생성 패키지 없이 순수 Dart로 작성되므로 build_runner를 돌릴 필요가 없습니다.
Flutter 앱에서 http나 dio로 받은 응답을 Map<String, dynamic> 그대로 위젯에 넘기던 코드를 모델 클래스로 정리하고 싶을 때, 또는 json_serializable을 도입하기 전 작은 프로젝트에서 바로 쓸 직렬화 코드가 필요할 때 맞습니다.
타입 이름에 최상위 클래스 이름을 적습니다(예: Store).lib/models/ 아래 파일에 붙여넣습니다. import는 필요 없습니다.Store.fromJson(jsonDecode(response.body) as Map<String, dynamic>)으로 객체를 만들고, 보낼 때는 jsonEncode(store.toJson())을 씁니다.{
"storeId": 77,
"storeName": "Mapo Kimbap",
"isOpen": true,
"rating": 4.7,
"menuItems": [
{ "name": "Tuna Kimbap", "price": 4500, "soldOut": false },
{ "name": "Ramyeon", "price": 5000, "soldOut": true, "spicy": 2 }
]
}class Store {
final int storeId;
final String storeName;
final bool isOpen;
final double rating;
final List<MenuItem> menuItems;
Store({
required this.storeId,
required this.storeName,
required this.isOpen,
required this.rating,
required this.menuItems,
});
factory Store.fromJson(Map<String, dynamic> json) => Store(
storeId: json['storeId'] as int,
storeName: json['storeName'] as String,
isOpen: json['isOpen'] as bool,
rating: (json['rating'] as num).toDouble(),
menuItems: (json['menuItems'] as List<dynamic>).map((e) => MenuItem.fromJson(e as Map<String, dynamic>)).toList(),
);
Map<String, dynamic> toJson() => {
'storeId': storeId,
'storeName': storeName,
'isOpen': isOpen,
'rating': rating,
'menuItems': menuItems.map((e) => e.toJson()).toList(),
};
}
class MenuItem {
final String name;
final int price;
final bool soldOut;
final int? spicy;
MenuItem({
required this.name,
required this.price,
required this.soldOut,
this.spicy,
});
factory MenuItem.fromJson(Map<String, dynamic> json) => MenuItem(
name: json['name'] as String,
price: json['price'] as int,
soldOut: json['soldOut'] as bool,
spicy: json['spicy'] as int?,
);
Map<String, dynamic> toJson() => {
'name': name,
'price': price,
'soldOut': soldOut,
'spicy': spicy,
};
}
menuItems 배열 요소는 MenuItem 클래스가 되고 fromJson 안에서 .map(...).toList()로 변환됩니다. rating은 (json['rating'] as num).toDouble()로 읽어 정수가 와도 안전하고, 일부 메뉴에만 있는 spicy는 int?이며 생성자에서 required가 빠집니다.
final, 생성자는 이름 있는 파라미터({required this.x})로 만듭니다.factory X.fromJson(Map<String, dynamic> json)과 Map<String, dynamic> toJson()을 직접 작성해 패키지 의존성이 없습니다.fromJson/toJson을 호출하도록 연결됩니다.double 필드는 (as num).toDouble()로 읽어, JSON에 4처럼 정수로 와도 캐스팅 오류가 나지 않습니다.null이 섞인 필드는 nullable(int?)이 되고 fromJson에서 null을 그대로 통과시킵니다.dynamic, class·is 같은 Dart 예약어 키는 뒤에 _를 붙입니다.typedef Root = List<RootItem>;을 만듭니다.FutureBuilder나 Riverpod·Bloc 상태에 Map을 그대로 들고 다니면 키 오타가 런타임에야 드러납니다. 생성된 클래스로 바꾸면 store.menuItems.first.price처럼 자동완성과 타입 검사를 받을 수 있습니다.
shared_preferences나 파일에 jsonEncode(store.toJson())으로 저장하고 앱 시작 시 fromJson으로 복원하는 캐시를 짧게 구현할 수 있습니다.
필드 목록과 타입을 먼저 확인한 뒤, 프로젝트가 커지면 같은 필드에 @JsonSerializable()을 붙여 코드 생성 방식으로 옮겨 갈 수 있습니다.
5000.0을 정수 5000으로 읽습니다. 반면 Dart의 jsonDecode는 5000.0을 double로 유지하므로 as int에서 오류가 납니다. 소수점이 붙어 올 수 있는 금액·좌표 필드는 double로 고쳐 주세요.toJson은 nullable 필드가 null이어도 키를 그대로 넣습니다('spicy': null). 서버가 null 키를 싫어하면 조건부로 빼야 합니다.String입니다. DateTime.parse(json['createdAt'] as String)로 직접 바꿔야 합니다.copyWith, ==/hashCode, toString은 만들지 않습니다. 필요하면 freezed나 equatable을 고려하세요.dynamic 필드는 검사 없이 값을 그대로 담으므로, 실제 타입을 알게 되면 바꾸는 것이 좋습니다.출력은 패키지 없이 손으로 쓴 형태의 fromJson/toJson입니다. 필드 선언부만 가져가 @JsonSerializable()과 part 'store.g.dart';를 붙이고 dart run build_runner build를 돌리면 코드 생성 방식으로 바꿀 수 있습니다.
type 'int' is not a subtype of type 'double' 오류가 나요.직접 as double로 캐스팅하면 JSON의 정수 값에서 이 오류가 납니다. 이 도구는 double 필드를 (as num).toDouble()로 읽어 막아 두었으니, 손으로 고친 필드가 있다면 같은 방식으로 바꿔 주세요.
[ {...}, {...} ])은 어떻게 디코딩하나요?최상위 배열이면 typedef와 요소 클래스가 생깁니다. (jsonDecode(body) as List<dynamic>).map((e) => RootItem.fromJson(e as Map<String, dynamic>)).toList()처럼 요소마다 fromJson을 호출하면 됩니다.
출력은 Dart 2.12 이후의 sound null safety 문법(int?, required)을 씁니다. null safety 이전 프로젝트에서는 ?와 required를 지워야 컴파일됩니다.