알쓸전컴(알아두면 쓸모있는 전자 컴퓨터)

Flutter Json DeSerializable 와 Json List DeSerializable 본문

Flutter,Dart

Flutter Json DeSerializable 와 Json List DeSerializable

백곳 2019. 7. 18. 22:46

Spring 을 BackEnd 로 사용 하며 DB의 데이터를 가지고 올때 JSON 의 형태로 리스트로 받을때 

 

필요하여 분석 하였습니다. 

 

일단 기본참고 자료는 Flutter 공식 문서 입니다. 

 

https://flutter.dev/docs/development/data-and-backend/json

 

JSON and serialization

It is hard to think of a mobile app that doesn't need to communicate with aweb server or easily store structured data at some point. When makingnetwork-connected apps, the chances are that it needs to consume some good oldJSON, sooner or later.This guide l

flutter.dev

 

위에 사이트에 보면 처음에는 직접 코드 작성 방법 2번 째는 어노테이션을 사용하여 자동으로 코드를 작성해주는 방법이 있습니다. 

 

원리를 알기 위해서 첫번째 방법을 하는것도 좋지만 공식 문서만 봐도 첫번째 직접 코드 작성은 직관적이기 때문에 

 

작성을 하지는 않겠습니다. 

 

먼저 어노테이션을 사용하기 위해 의존성 있는 플러그인 들을 설치해 줍니다. 

 

pubspec.yaml 파일에 

 

dependencies:

   json_annotation: ^2.0.0

dev_dependencies

   build_runner: ^1.0.0

   json_serializable: ^2.0.0

 

이렇게 설치를 해줍니다. 

 

그리고 나서 저는 

 

FoodList.dart 라는 파일에 

아래와 같이 작성해 주었습니다. 

import 'package:json_annotation/json_annotation.dart';

part 'FoodList.g.dart';

@JsonSerializable()
class FoodTableItem {
  String fooduuid;
  String foodName;
  String subTitle;
  String mainFoodImage;
  String description;
  double price;
  double heart;
  double disHeart;
  String foodCategory;
  String createTime;
  String weatherType;
  int freeze;
  int coldStorage;
  int shelfLife;
  int requireCooker;
  FoodTableItem();

  factory FoodTableItem.fromJson(Map<String, dynamic> json) =>
      _$FoodTableItemFromJson(json);
  Map<String, dynamic> toJson() => _$FoodTableItemToJson(this);
}

여기서 FoodList.g.dart 는 

꼭 현재 작성중인 FoodList.dart 파일에  FoodList.g.dart 글자를 똑같이 만들어 줘야 합니다. 

그러면 나중에 어노테이션(@)으로 인한 코드가 생성될 파일을 만들때 해당 FoodList.g.dart  로 만들게 됩니다. 

 

그리고 나머지 부부중 

factory FoodTableItem.fromJson(Map<String, dynamic> json) =>
      _$FoodTableItemFromJson(json);
  Map<String, dynamic> toJson() => _$FoodTableItemToJson(this);

 

이부분은 똑같이 FoodTableItem 만 Class 이름과 맞춰 줍니다. 

 

그리고 나서 터미널에서 

 

flutter pub run build_runner build

을 적으면 코드가 만들어 지기 시작 합니다. 

 

그후에 사용할수 있습니다. 

 

  Future<dynamic> findfoodlist(Foodsearch searchitem) async {
    Map<String, String> queryParameters = {
      'foodCategory': searchitem.categoryInfo.category,
      'searchtext': searchitem.searchtext,
      'page': searchitem.nowpage.toString()
    };
    var getfooduri =
        Uri.http(Preferance.backEndSite, '/GetFoodTable', queryParameters);

    http.Response response = await http.get(getfooduri);
    var decodejson = jsonDecode(response.body);
    var Listitem =
        (decodejson as List).map((p) => FoodTableItem.fromJson(p)).toList();

    return jsonDecode(response.body);
  }

 

위에 코드는 제가사용 해본 코드 인데요 

 

    List<FoodTableItem> Listitem =
        (decodejson as List).map((p) => FoodTableItem.fromJson(p)).toList();

 

이부분은 {[Object,Object,Object]} 이런식의 JSON 형태일때 List 로써 DeSerializable 을 한 예를 보여준 것입니다.

 

보통 BackEnd 에서 DB를 조회 할때는 많이 이런 코드가 필요 하기 때문입니다. 

 

일반적인 코드에서는 

 

FoodTableItem.fromJson(p)  p 부분에 JSON 형태의 문자열을 집여 넣으면 바로 객체로 리턴 됩니다. 

 

 

Comments