[Flutter] Json 파일 파싱하기

찌니·2022년 11월 12일
0

Flutter

목록 보기
3/13

데이터를 가져올때, json 형식으로 가져오는 경우가 많다.
그래서 오늘은 json 파일을 모델 형식으로 바꿔보자 !
먼저 프로젝트 내 assets에 파일을 추가해준 후


pubspec.yaml의 assets에 루트를 추가해준다. 한개의 파일이면 assets/a.json 형식으로 넣어줘도 상관없다.

예시의 json 파일이다. 한 모델의 리스트 형태를 하고 있다.

Place class

class Place {
  String? id;
  String? title;
  String? latitude;
  String? longitude;
  String? jibunAddress;
  String? roadAddress;
  String? description;
  String? image;

  Place({
    this.id,
    this.title,
    this.latitude,
    this.longitude,
    this.jibunAddress,
    this.roadAddress,
    this.description,
    this.image,
  });

  factory Place.fromJson(Map<String, dynamic> json) => Place(
        id: json["id"],
        title: json["title"],
        latitude: json["latitude"],
        longitude: json["longitude"],
        jibunAddress: json["jibunAddress"],
        roadAddress: json["roadAddress"],
        description: json["description"],
        image: json["image"],
      );
}

json을 map 형식으로 받아서 place 모델로 변경해주고 있다.
하지만 예시의 json 파일의 형식은 List<Place.>이다.
이때는 리스트 모델을 하나 더 생성해주어야 한다.

PlaceList class

class PlaceList {
  final List<Place>? places;
  PlaceList({this.places});

  factory PlaceList.fromJson(String jsonString) {
    List<dynamic> listFromJson = json.decode(jsonString);
    List<Place> places = <Place>[];

    places = listFromJson.map((place) => Place.fromJson(place)).toList();
    return PlaceList(places: places);
  }
}

placeList.fromJson에서 String을 받고 있다. json 파일을 String 형태로 바꿔준 후, json.decode()로 List<dynamic.>으로 변환한다.
그리고 List를 한개씩 Place.fromJson으로 Place 모델로 변환 후, 리스트로 받은 결과이다
결과는 List<Place.>가 된다

사용하는 부분이다

profile
찌니's develog

0개의 댓글