What is JSON?
JSON (JavaScript Object Notation) is the standard format for data exchange between clients and servers. Dart's dart:convert library provides jsonDecode and jsonEncode for parsing and producing JSON.
Decoding JSON
import 'dart:convert';
void main() {
// JSON string to Dart object:
String jsonStr = '{"name":"Alice","age":30,"active":true}';
Map<String, dynamic> user = jsonDecode(jsonStr);
print(user['name']); // Alice
print(user['age']); // 30
// JSON array:
String jsonArray = '[1, 2, 3, 4, 5]';
List<dynamic> numbers = jsonDecode(jsonArray);
print(numbers.cast<int>()); // [1, 2, 3, 4, 5]
// Complex nested JSON:
String complex = '''
{
"users": [
{"id": 1, "name": "Alice", "roles": ["admin", "user"]},
{"id": 2, "name": "Bob", "roles": ["user"]}
],
"total": 2
}
''';
var data = jsonDecode(complex) as Map<String, dynamic>;
var users = data['users'] as List;
for (var u in users) {
print('$${u['name']}: $${u['roles'].join(', ')}');
}
}
Encoding to JSON
import 'dart:convert';
void main() {
var user = {
'name': 'Bob',
'age': 25,
'scores': [98, 87, 92],
'address': {'city': 'Phnom Penh', 'country': 'Cambodia'}
};
// Compact JSON:
String compact = jsonEncode(user);
print(compact);
// Pretty-printed JSON:
var encoder = JsonEncoder.withIndent(' ');
print(encoder.convert(user));
}
JSON to Model Classes
class Product {
final int id;
final String name;
final double price;
final bool inStock;
final List<String> tags;
Product({
required this.id,
required this.name,
required this.price,
required this.inStock,
required this.tags,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'] as int,
name: json['name'] as String,
price: (json['price'] as num).toDouble(),
inStock: json['in_stock'] as bool,
tags: List<String>.from(json['tags'] ?? []),
);
}
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'price': price,
'in_stock': inStock,
'tags': tags,
};
@override String toString() => 'Product($id: $name @ \$$price)';
}
void main() {
var json = '{"id":1,"name":"Dart Book","price":29.99,"in_stock":true,"tags":["programming","dart"]}';
var product = Product.fromJson(jsonDecode(json));
print(product); // Product(1: Dart Book @ $29.99)
print(jsonEncode(product.toJson()));
}
Nested JSON Models
class Address {
final String city, country;
Address({required this.city, required this.country});
factory Address.fromJson(Map<String, dynamic> j) =>
Address(city: j['city'], country: j['country']);
Map<String, dynamic> toJson() => {'city': city, 'country': country};
}
class User {
final String name;
final Address address;
final List<Product> cart;
User({required this.name, required this.address, required this.cart});
factory User.fromJson(Map<String, dynamic> j) => User(
name: j['name'],
address: Address.fromJson(j['address']),
cart: (j['cart'] as List).map((p) => Product.fromJson(p)).toList(),
);
}
🧠 Quiz
1. Which function converts a JSON string to a Dart object?
- A) jsonParse
- B) json.parse
- C) jsonDecode ✅
- D) fromJson
2. What does jsonEncode return?
- A) A Map
- B) A JSON-formatted String ✅
- C) A Future
- D) A List
Summary
Use jsonDecode(String) to parse JSON into Dart maps/lists. Use jsonEncode(Object) to convert Dart objects to JSON strings. Create model classes with fromJson factory constructors and toJson() methods for type-safe JSON handling. Use JsonEncoder.withIndent for pretty-printed output.