Json 직렬화 패키지

Json 데이터를 자동으로 직렬화하는 패키지를 설치하고 사용합니다.

Json 자동 직렬화 관련 패키지 설치

pubspec.yaml
dependencies:
  #json 직렬화 관련
  json_annotation: ^3.0.1
  
dev_dependencies:
  flutter_test:
    sdk: flutter
  
  #json 직렬화
  build_runner: ^1.10.0

  #json 직렬화
  json_serializable: ^3.4.1

dependency_overrides:
  #json 직렬화
  analyzer: '0.39.14'

build_runner 버그인지...analyzer를 0.39.14 버전으로 고정을 해야지만 정상 작동이 됩니다. 향후 최신 버전에서는 해결이 될 경우 analyzer 버전을 최신으로 사용해도 됩니다.

사용법

booking.dart
import 'package:json_annotation/json_annotation.dart';

//Json직렬화 코드가 생성될 *.g.dart 파일
//데이터 클래스 booking.dart 파일이면 booking.g.dart 파일이 생성된
part 'booking.g.dart';

//자동으로 Json 직렬화 처리를 알려주는 코드 
@JsonSerializable()

class Booking {
  int id;
  String deptCode;
  Booking(this.id, this.deptCode);
  
  //_$BookingFromJson 및 _$BookingToJson 으로 작
  factory Booking.fromJson(Map<String, dynamic> json) =>
      _$BookingFromJson(json);
  Map<String, dynamic> toJson() => _$BookingToJson(this);
}

프로젝트 루트 폴더에서 아래 명령어를 실행하면 *.g.dart 파일이 생성됩니다.

$ flutter pub run build_runner watch

자동 생성 결과

데이터가 적은 경우 직접 작성해도 되지만 데이터가 많아지면 모두 코딩을 해야 하기 때문에 무척 힘이 드는데...자동 직렬화로 편해 질 수 있습니다.

Last updated

Was this helpful?