상세 컨텐츠

본문 제목

JSON 데이터 파싱: Flutter에서 효율적으로 다루는 방법

공부/Flutter

by micalcomanie 2025. 1. 7. 02:13

본문

728x90
반응형
SMALL

JSON(JavaScript Object Notation)은 서버와 클라이언트 간 데이터를 교환하는 데 널리 사용되는 형식입니다.
Flutter에서 JSON 데이터를 파싱하는 방법을 단계별로 설명하겠습니다.


1. JSON 파싱 기초

Flutter에서 JSON 데이터를 다루려면 dart:convert 라이브러리의 json.decode()json.encode()를 사용합니다.

1.1 JSON 디코딩

서버에서 받은 JSON 문자열을 Dart 객체로 변환합니다:

import 'dart:convert';

void main() {
  String jsonString = '{"name": "John", "age": 30}';
  Map<String, dynamic> user = json.decode(jsonString);
  print(user['name']); // John
}

1.2 JSON 인코딩

Dart 객체를 JSON 문자열로 변환합니다:

import 'dart:convert';

void main() {
  Map<String, dynamic> user = {'name': 'John', 'age': 30};
  String jsonString = json.encode(user);
  print(jsonString); // {"name":"John","age":30}
}

2. 단일 객체 파싱

단일 JSON 객체를 Dart 객체로 변환합니다.

예제 JSON

{
  "id": 1,
  "title": "Flutter JSON Parsing",
  "completed": true
}

예제 코드

import 'dart:convert';

class Task {
  final int id;
  final String title;
  final bool completed;

  Task({required this.id, required this.title, required this.completed});

  factory Task.fromJson(Map<String, dynamic> json) {
    return Task(
      id: json['id'],
      title: json['title'],
      completed: json['completed'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'completed': completed,
    };
  }
}

void main() {
  String jsonString = '{"id": 1, "title": "Flutter JSON Parsing", "completed": true}';
  Map<String, dynamic> jsonMap = json.decode(jsonString);

  Task task = Task.fromJson(jsonMap);
  print(task.title); // Flutter JSON Parsing

  String encodedJson = json.encode(task.toJson());
  print(encodedJson); // {"id":1,"title":"Flutter JSON Parsing","completed":true}
}

3. 리스트 파싱

JSON 배열을 Dart 리스트로 변환합니다.

예제 JSON

[
  {"id": 1, "title": "Task 1", "completed": false},
  {"id": 2, "title": "Task 2", "completed": true}
]

예제 코드

void main() {
  String jsonString = '[{"id": 1, "title": "Task 1", "completed": false}, {"id": 2, "title": "Task 2", "completed": true}]';
  List<dynamic> jsonList = json.decode(jsonString);

  List<Task> tasks = jsonList.map((json) => Task.fromJson(json)).toList();

  tasks.forEach((task) {
    print(task.title);
  });
  // Task 1
  // Task 2
}

4. 복잡한 JSON 구조 파싱

중첩된 JSON 데이터를 Dart 객체로 변환합니다.

예제 JSON

{
  "user": {
    "id": 1,
    "name": "John",
    "tasks": [
      {"id": 1, "title": "Task 1", "completed": false},
      {"id": 2, "title": "Task 2", "completed": true}
    ]
  }
}

예제 코드

class User {
  final int id;
  final String name;
  final List<Task> tasks;

  User({required this.id, required this.name, required this.tasks});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      tasks: (json['tasks'] as List).map((task) => Task.fromJson(task)).toList(),
    );
  }
}

void main() {
  String jsonString = '{"user": {"id": 1, "name": "John", "tasks": [{"id": 1, "title": "Task 1", "completed": false}, {"id": 2, "title": "Task 2", "completed": true}]}}';
  Map<String, dynamic> jsonMap = json.decode(jsonString);

  User user = User.fromJson(jsonMap['user']);
  print(user.name); // John
  print(user.tasks[0].title); // Task 1
}

5. 에러 처리

JSON 파싱 중 발생할 수 있는 에러를 처리합니다.

5.1 예외 처리

try {
  String jsonString = '{"name": "John"}';
  Map<String, dynamic> jsonMap = json.decode(jsonString);
  print(jsonMap['age']); // Null 발생
} catch (error) {
  print('Error: $error');
}

5.2 필드가 없는 경우 기본값 설정

factory Task.fromJson(Map<String, dynamic> json) {
  return Task(
    id: json['id'] ?? 0,
    title: json['title'] ?? 'Untitled',
    completed: json['completed'] ?? false,
  );
}

6. 결론

Flutter에서 JSON 데이터를 파싱하는 방법은 간단하지만, 복잡한 구조에서도 유연하게 처리할 수 있습니다.
이 글에서 다룬 내용을 활용해 서버와 원활히 통신하고 데이터를 효율적으로 처리해 보세요.
다음 글에서는
실시간 API 데이터 활용을 다룰 예정입니다.


참고 자료

728x90
반응형
LIST

관련글 더보기