JSON(JavaScript Object Notation)은 서버와 클라이언트 간 데이터를 교환하는 데 널리 사용되는 형식입니다.
Flutter에서 JSON 데이터를 파싱하는 방법을 단계별로 설명하겠습니다.
Flutter에서 JSON 데이터를 다루려면 dart:convert 라이브러리의 json.decode()와 json.encode()를 사용합니다.
서버에서 받은 JSON 문자열을 Dart 객체로 변환합니다:
import 'dart:convert';
void main() {
String jsonString = '{"name": "John", "age": 30}';
Map<String, dynamic> user = json.decode(jsonString);
print(user['name']); // John
}
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}
}
단일 JSON 객체를 Dart 객체로 변환합니다.
{
"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}
}
JSON 배열을 Dart 리스트로 변환합니다.
[
{"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
}
중첩된 JSON 데이터를 Dart 객체로 변환합니다.
{
"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
}
JSON 파싱 중 발생할 수 있는 에러를 처리합니다.
try {
String jsonString = '{"name": "John"}';
Map<String, dynamic> jsonMap = json.decode(jsonString);
print(jsonMap['age']); // Null 발생
} catch (error) {
print('Error: $error');
}
factory Task.fromJson(Map<String, dynamic> json) {
return Task(
id: json['id'] ?? 0,
title: json['title'] ?? 'Untitled',
completed: json['completed'] ?? false,
);
}
Flutter에서 JSON 데이터를 파싱하는 방법은 간단하지만, 복잡한 구조에서도 유연하게 처리할 수 있습니다.
이 글에서 다룬 내용을 활용해 서버와 원활히 통신하고 데이터를 효율적으로 처리해 보세요.
다음 글에서는 실시간 API 데이터 활용을 다룰 예정입니다.
Flutter 네트워크 통신 기초: HTTP 요청 보내기 (0) | 2025.01.06 |
---|---|
물리 효과를 활용한 고급 애니메이션 구현 (1) | 2025.01.03 |
제스처와 고급 물리 효과를 결합하는 방법 (0) | 2025.01.03 |
제스처와 애니메이션 결합하기 (0) | 2025.01.03 |
버튼 클릭 시 색상 변화 애니메이션 구현하기 (0) | 2025.01.03 |