How to Parse JSON in Flutter: Simple Guide with Example
In Flutter, you parse JSON by importing
dart:convert and using jsonDecode() to convert a JSON string into a Dart map or list. Then, you can access the data like a normal Dart object or convert it into custom model classes.Syntax
To parse JSON in Flutter, first import dart:convert. Use jsonDecode() to convert a JSON string into a Dart object (usually a Map<String, dynamic> or List). You can then access the data by keys or indexes.
import 'dart:convert';- imports JSON utilities.jsonDecode(jsonString)- parses JSON string.- Result is a Dart map or list depending on JSON structure.
dart
import 'dart:convert'; void main() { String jsonString = '{"name": "Alice", "age": 30}'; Map<String, dynamic> user = jsonDecode(jsonString); print(user['name']); // Alice }
Output
Alice
Example
This example shows how to parse a JSON string representing a user, then print the user's name and age. It demonstrates converting JSON to a Dart map and accessing its values.
dart
import 'dart:convert'; void main() { String jsonString = '{"name": "Bob", "age": 25}'; Map<String, dynamic> user = jsonDecode(jsonString); print('Name: ' + user['name']); print('Age: ' + user['age'].toString()); }
Output
Name: Bob
Age: 25
Common Pitfalls
Common mistakes include:
- Not importing
dart:convert. - Trying to parse JSON without using
jsonDecode(). - Assuming JSON is always a map; sometimes it can be a list.
- Not handling null or missing keys safely.
Always check the JSON structure before parsing and consider using model classes for complex data.
dart
import 'dart:convert'; void main() { String jsonString = '[{"name": "Carol"}, {"name": "Dave"}]'; // Wrong: expecting a Map but JSON is a List // Map<String, dynamic> data = jsonDecode(jsonString); // This causes error // Right: parse as List List<dynamic> data = jsonDecode(jsonString); print(data[0]['name']); // Carol }
Output
Carol
Quick Reference
- Import:
import 'dart:convert'; - Parse JSON string:
jsonDecode(jsonString) - Result type:
Map<String, dynamic>orList<dynamic> - Access data: Use map keys or list indexes
- Convert to model: Create Dart classes with
fromJson()methods for complex data
Key Takeaways
Use dart:convert's jsonDecode() to parse JSON strings into Dart objects.
JSON can be a Map or List; always check the structure before parsing.
Import dart:convert to access JSON parsing functions.
Handle missing or null keys safely to avoid runtime errors.
For complex JSON, create Dart model classes with fromJson() methods.