티스토리 뷰

Flutter

dart] json_serializable

_히처리 2023. 7. 29. 15:47

플러터에서  json_serializable 패키지를 사용하면, 객체를 json으로 변환하거나, json을 객체로 쉽게 만들 수 있다.

 

먼저 pubspec.yaml에 다음의 정보를 추가하자.

dependencies:
  json_annotation: ^4.8.0

dev_dependencies:
  build_runner: ^2.3.3
  json_serializable: ^6.6.0

 

json_serializable을 적용할 클래스에 다음 작업을 해야 한다.

1. part <파일명>.g.dart 추가하기

2. 클래스에 @JsonSerializable를 추가하기

3. fromJson 명명된 생성자 추가하기 : 생성자는 _$<클래스이름>FromJson() 함수를 사용한다.

4. toJson 메서드 추가하기 : 메서드는 _$<클래스이름>ToJson() 함수를 사용한다.

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable()
class Person {
  final String name;
  fianl int age;

  Person({required this.name, required this.age});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

 

 

 

그리고 터미널에 다음 명령을 실행하자.

dart run build_runner build

 

그러면 <파일명>.g.dart 이 생성되고, 해당 파일에 _$로 시작하는 함수가 포함되어 있다.

댓글
공지사항