JSON & Models

June 02, 2026 1 min read

APIs return JSON; convert it into typed Dart classes for safety and convenience.

class Product {
  final int id;
  final String title;
  final double price;
  Product({required this.id, required this.title, required this.price});

  factory Product.fromJson(Map<String, dynamic> j) => Product(
    id: j['id'],
    title: j['title'],
    price: (j['price'] as num).toDouble(),
  );

  Map<String, dynamic> toJson() => {'id': id, 'title': title, 'price': price};
}
Tip: For big models, code generators like json_serializable write fromJson/toJson for you.

Summary

Write fromJson/toJson to map between JSON and typed models — or generate them with json_serializable for large apps.