Tool Kumar 도구

JSON을 Dart 모델로 변환

Flutter API 응답에 맞는 Dart 모델을 생성합니다. 출력의 중첩 클래스마다 final 필드, const 생성자, fromJson 팩토리, toJson 메서드가 들어 있습니다.

도구 사용 방법

  1. 필드 구성이 서로 다른 레코드까지 포함해 대표적인 응답을 붙여넣습니다.
  2. 생성된 출력을 검토하고, 필요하면 ‘루트 이름’을 바꿉니다.
  3. 코드를 복사하거나 다운로드한 뒤, 타입이 API 명세와 맞는지 확인합니다.

사용 예제

내장 변환기가 생성한 출력입니다. 두 항목의 price 값에서는 부동소수점 필드가, null과 문자열인 note 값에서는 null 허용 필드가 추론됩니다.

입력

{
  "user-id": 42,
  "profile": {
    "city": "London",
    "created_at": "2026-10-14T09:00:00Z"
  },
  "items": [
    {
      "price": 12,
      "note": null
    },
    {
      "price": 12.5,
      "note": "gift"
    }
  ]
}

출력

class Root {
  final int userId;
  final Profile profile;
  final List<Item> items;

  const Root({
    required this.userId,
    required this.profile,
    required this.items,
  });

  factory Root.fromJson(Map<String, dynamic> json) => Root(
    userId: json['user-id'] as int,
    profile: Profile.fromJson(json['profile'] as Map<String, dynamic>),
    items: (json['items'] as List<dynamic>).map((e) => Item.fromJson(e as Map<String, dynamic>)).toList(),
  );

  Map<String, dynamic> toJson() => {
    'user-id': userId,
    'profile': profile.toJson(),
    'items': items.map((e) => e.toJson()).toList(),
  };
}

class Profile {
  final String city;
  final String createdAt;

  const Profile({
    required this.city,
    required this.createdAt,
  });

  factory Profile.fromJson(Map<String, dynamic> json) => Profile(
    city: json['city'] as String,
    createdAt: json['created_at'] as String,
  );

  Map<String, dynamic> toJson() => {
    'city': city,
    'created_at': createdAt,
  };
}

class Item {
  final double price;
  final String? note;

  const Item({
    required this.price,
    this.note,
  });

  factory Item.fromJson(Map<String, dynamic> json) => Item(
    price: (json['price'] as num).toDouble(),
    note: json['note'] as String?,
  );

  Map<String, dynamic> toJson() => {
    'price': price,
    'note': note,
  };
}

Flutter에서 모델 사용하기

dart:convert를 import하고 생성된 클래스를 모델 파일에 붙여넣습니다. 디코딩한 응답 맵을 Root.fromJson에 전달합니다. jsonEncode는 생성된 toJson 메서드를 호출합니다.

프로젝트에서 이미 json_serializable을 사용한다면, 생성된 JSON 메서드를 두 벌로 관리하지 말고 필드를 그 워크플로에 맞게 옮기는 것이 좋습니다.

import 'dart:convert';

final model = Root.fromJson(jsonDecode(responseBody) as Map<String, dynamic>);
final text = jsonEncode(model.toJson());

옵션 및 예외 사항

  • user-id 같은 JSON 키는 camelCase 필드로 매핑됩니다. 생성된 JSON 메서드는 원래 키를 그대로 사용합니다.
  • 정수와 소수인 가격은 double로 합쳐집니다. 디코더가 num으로 캐스팅한 뒤 toDouble을 호출하므로 두 샘플 값 모두 처리됩니다.
  • null과 문자열이 함께 나오면 String?이 됩니다. null로만 관찰된 필드는 의도한 타입을 알 수 없으므로 dynamic으로 남습니다.
  • 날짜는 String으로 남으므로 DateTime 파싱은 직접 검토해야 합니다. 웹용으로 컴파일된 Dart는 모든 큰 정수를 정확하게 표현하지 못합니다.

개인정보 보호 기본 적용

문서는 이 브라우저에만 보관됩니다. Tool Kumar는 기기 안에서 파싱, 변환, 다운로드 파일 생성을 처리하며 계정이나 업로드 과정이 필요하지 않습니다.

JSON을 Dart 모델로 변환 자주 묻는 질문

json_serializable 어노테이션을 생성하나요?
아니요. fromJson과 toJson 메서드를 직접 작성합니다. @JsonSerializable 어노테이션, part 파일, build_runner 단계는 없습니다.
null 안전성은 어떻게 처리하나요?
null이 나오거나 일부 레코드에 없는 필드는 null 허용으로 추론됩니다. null이 아닌 필드는 required 생성자 인수를 사용하고, null로만 관찰된 필드는 dynamic을 사용합니다.
중첩 객체 배열도 변환할 수 있나요?
네. 샘플에서는 List<Item>이 만들어집니다. 각 입력 요소를 Item.fromJson으로 매핑하고, 인코딩할 때는 항목마다 toJson을 호출합니다.
Flutter 패키지가 필요한가요?
생성된 모델은 Dart 핵심 타입만 사용합니다. dart:convert로 응답 텍스트를 디코딩한 뒤 Root.fromJson을 호출합니다.

관련 도구

JSON을 Swift 모델로 변환, JSON을 Kotlin 데이터 클래스로 변환 및 JSON Schema 생성기.