본문 바로가기
Category/Flutter

Dart에서 JSON 쉽게 다루기 : jsonDecode 사용법과 예제

by Corinee 2024. 11. 3.
728x90
반응형

jsonDecode 설명 및 사용 예시

jsonDecode는 Dart의 내장 라이브러리인 dart:convert에 포함된 함수로, JSON 문자열을 Dart 객체(예: Map, List)로 변환해 주는 역할을 합니다. 이 함수는 JSON 데이터를 쉽게 처리할 수 있게 해주며, REST API로부터 받은 JSON 형식의 응답을 디코딩하는 데 자주 사용됩니다.

주요 특징:

  • JSON 문자열을 Dart 객체로 변환합니다.
  • 반환된 Dart 객체는 JSON의 구조에 따라 Map<String, dynamic> 혹은 List<dynamic> 타입이 됩니다.
  • JSON 구조가 중첩된 경우에도 jsonDecode는 이를 적절히 변환해줍니다.

사용 예시:

import 'dart:convert';

void main() {
  // JSON 문자열 예제
  String jsonString = '{"title": "Flutter Tutorial", "views": 1500, "isPublished": true}';
  
  // JSON 문자열을 Dart Map으로 디코딩
  Map<String, dynamic> decodedJson = jsonDecode(jsonString);
  
  // 디코딩된 데이터 사용
  print('Title: ${decodedJson['title']}'); // 출력: Title: Flutter Tutorial
  print('Views: ${decodedJson['views']}'); // 출력: Views: 1500
  print('Is Published: ${decodedJson['isPublished']}'); // 출력: Is Published: true

  // JSON 리스트 예제
  String jsonArray = '[{"name": "Item1"}, {"name": "Item2"}]';
  List<dynamic> decodedList = jsonDecode(jsonArray);

  // 리스트 내 아이템 출력
  for (var item in decodedList) {
    print(item['name']); // 출력: Item1, Item2
  }
}

주의사항:

  • jsonDecode 함수는 문자열이 JSON 형식이 아니거나 파싱할 수 없는 경우 예외를 던집니다. 이를 방지하기 위해 try-catch 블록으로 오류를 처리하는 것이 좋습니다.
try {
  var result = jsonDecode('{"invalid json}');
} catch (e) {
  print('Error decoding JSON: $e');
}

결론:

jsonDecode는 Dart에서 JSON 데이터를 쉽게 다룰 수 있도록 해주는 유용한 함수입니다. API 요청 응답이나 JSON 파일을 처리할 때 이를 활용하여 Dart 객체로 변환하고 데이터를 다룰 수 있습니다.