<Flutter> Flutter에서 JSON 인코딩 및 디코딩하기

반응형

Flutter 애플리케이션에서 데이터를 처리할 때 JSON 형식은 매우 일반적으로 사용됩니다. 이 글에서는 Flutter에서 JSON 데이터를 인코딩하고 디코딩하는 방법을 자세히 살펴보겠습니다.

JSON이란?

JSON(JavaScript Object Notation)은 경량의 데이터 교환 형식입니다. 이 형식은 사람이 읽고 쓰기 쉽고, 기계가 분석하고 생성하기도 쉽습니다.

Flutter에서 JSON 인코딩하기

Flutter에서는 dart:convert 라이브러리의 jsonEncode 함수를 사용하여 객체를 JSON 문자열로 변환합니다.

import 'dart:convert';

void main() {
  Map<String, dynamic> user = {
    'name': '홍길동',
    'age': 30,
    'email': 'hong@gmail.com'
  };

  String jsonString = jsonEncode(user);
  print(jsonString);
}

위의 코드는 user 맵을 JSON 문자열로 변환하고 출력합니다.

Flutter에서 JSON 디코딩하기

dart:convert 라이브러리의 jsonDecode 함수를 사용하여 JSON 문자열을 Dart 객체로 변환합니다.

import 'dart:convert';

void main() {
  String jsonString = '{"name": "홍길동", "age": 30, "email": "hong@gmail.com"}';
  Map<String, dynamic> user = jsonDecode(jsonString);

  print(user['name']);
  print(user['age']);
  print(user['email']);
}

위의 코드는 JSON 문자열을 Dart 맵으로 변환하고 해당 값을 출력합니다.

복잡한 JSON 다루기

실제 애플리케이션에서는 단순한 JSON보다 훨씬 복잡한 JSON 데이터를 다루게 됩니다. 이 경우, 모델 클래스를 사용하여 JSON을 디코딩하는 것이 좋습니다.

예를 들어, 다음과 같은 JSON 데이터가 있다고 가정해봅시다.

{
  "name": "홍길동",
  "age": 30,
  "address": {
    "city": "서울",
    "country": "한국"
  }
}

이 데이터를 다루기 위해 다음과 같은 모델 클래스를 생성합니다.

class User {
  final String name;
  final int age;
  final Address address;

  User({required this.name, required this.age, required this.address});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'],
      age: json['age'],
      address: Address.fromJson(json['address'])
    );
  }
}

class Address {
  final String city;
  final String country;

  Address({required this.city, required this.country});

  factory Address.fromJson(Map<String, dynamic> json) {
    return Address(
      city: json['city'],
      country: json['country']
    );
  }
}

이제 User.fromJson 메서드를 사용하여 JSON 문자열을 User 객체로 변환할 수 있습니다.

import 'dart:convert';

void main() {
  String jsonString = '{"name": "홍길동", "age": 30, "address": {"city": "서울", "country": "한국"}}';
  Map<String, dynamic> userMap = jsonDecode(jsonString);
  User user = User.fromJson(userMap);

  print(user.name);
  print(user.address.city);
}

이렇게 Flutter에서 JSON 데이터를 쉽게 인코딩하고 디코딩할 수 있습니다. JSON을 다룰 때는 항상 데이터의 구조와 모델 클래스가 일치하는지 확인하는 것이 중요합니다.


이 글을 통해 Flutter에서 JSON 데이터를 어떻게 다루는지에 대한 기본적인 이해를 얻으셨기를 바랍니다. JSON은 데이터 교환의 핵심이므로 이를 잘 다루는 것은 매우 중요합니다.

Designed by JB FACTORY