JSON Handling in Dart
In this lesson, you will learn how to work with JSON data in Dart. JSON (JavaScript Object Notation) is the most common data format used in APIs, configuration files, and data exchange.
Almost every real-world Dart application interacts with JSON data, especially when communicating with servers.
What is JSON?
JSON is a lightweight data-interchange format that is easy for humans to read and easy for machines to parse.
A JSON object consists of key–value pairs.
{
"name": "Alice",
"age": 28,
"isActive": true
}
JSON Support in Dart
Dart provides built-in JSON support through the dart:convert library.
This library allows you to:
- Convert JSON strings into Dart objects
- Convert Dart objects into JSON strings
Importing dart:convert
import 'dart:convert';
Decoding JSON (JSON → Dart)
Decoding means converting a JSON string into a Dart object
(usually a Map or List).
import 'dart:convert';
void main() {
String jsonString = '{"name":"Alice","age":28}';
Map data = jsonDecode(jsonString);
print(data['name']);
print(data['age']);
}
Output:
- Alice
- 28
Encoding JSON (Dart → JSON)
Encoding means converting Dart objects into a JSON string.
import 'dart:convert';
void main() {
Map user = {
"name": "Bob",
"age": 32,
"isActive": true
};
String jsonString = jsonEncode(user);
print(jsonString);
}
Working with JSON Arrays
JSON data often contains lists of objects.
[
{"name":"Alice","age":28},
{"name":"Bob","age":32}
]
Decoding JSON arrays:
String jsonArray = '''
[
{"name":"Alice","age":28},
{"name":"Bob","age":32}
]
''';
List users = jsonDecode(jsonArray);
print(users[0]['name']);
print(users[1]['age']);
Using Strongly Typed Models (Best Practice)
In professional applications, you should not work directly with Maps. Instead, you use model classes.
Creating a Model Class
class User {
final String name;
final int age;
User({required this.name, required this.age});
factory User.fromJson(Map json) {
return User(
name: json['name'],
age: json['age'],
);
}
Map toJson() {
return {
"name": name,
"age": age,
};
}
}
Decoding JSON into Model Objects
String jsonString = '{"name":"Alice","age":28}';
Map data = jsonDecode(jsonString);
User user = User.fromJson(data);
print(user.name);
print(user.age);
Encoding Model Objects to JSON
User user = User(name: "Bob", age: 32);
String jsonString = jsonEncode(user.toJson());
print(jsonString);
Real-World Example: API Response
A typical API response looks like this:
{
"status": "success",
"users": [
{"name":"Alice","age":28},
{"name":"Bob","age":32}
]
}
Parsing it in Dart:
Map response = jsonDecode(apiResponse);
List users = (response['users'] as List)
.map((u) => User.fromJson(u))
.toList();
Common JSON Errors & Solutions
- Type mismatch: Use
dynamiccarefully - Missing keys: Use null checks
- Invalid JSON: Validate JSON before decoding
📝 Practice Exercises
Exercise 1
Decode a JSON string containing a list of products.
Exercise 2
Create a Dart model class for a product.
Exercise 3
Convert the Dart object back to JSON.
✅ Practice Answers
class Product {
String name;
double price;
Product(this.name, this.price);
factory Product.fromJson(Map json) {
return Product(json['name'], json['price']);
}
Map toJson() {
return {"name": name, "price": price};
}
}
What’s Next?
In the next lesson, you will learn how to build APIs using Dart, including sending and receiving JSON data from servers.