티스토리 뷰
반응형
플러터에서 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 이 생성되고, 해당 파일에 _$로 시작하는 함수가 포함되어 있다.
반응형
'Flutter' 카테고리의 다른 글
다트] 예외(Exception)와 에러(Error)의 차이점 (0) | 2023.07.27 |
---|---|
다트] 객체 동등성(equality) 구현하기, equaltable (0) | 2023.07.19 |
플러터] iOS, Anroid 플랫폼 확인하는 방법 (0) | 2023.07.15 |
플러터] AdMob 광고 추가하기 (0) | 2023.07.15 |
플러터] 조건에 따라서 위젯을 추가하는 방법 (0) | 2023.07.15 |
댓글
공지사항