JSON to Dart Class
Convert JSON objects to Dart classes with fromJson/toJson constructors for Flutter development.
Features
đ¯ Flutter Ready
- fromJson factory constructor
- toJson serialization method
- Nested class generation
- camelCase field names
đ Null Safety
- Dart 2.12+ null safety support
- Nullable types with ?
- Required constructor parameters
- Type-safe field access
âī¸ Equatable Support
- Optional Equatable extension
- Value equality comparison
- props list generation
- BLoC/Cubit compatible
Dart JSON Guide
Dart JSON Serialization
Dart classes can be manually serialized using fromJson/toJson methods or with code generation via json_serializable. Manual serialization is straightforward and requires no build step.
# pubspec.yaml (for Equatable support) dependencies: equatable: ^2.0.5
// Usage example
final json = {'id': 1, 'name': 'Alice'};
final user = Root.fromJson(json);
final backToJson = user.toJson();
Using generated Dart models in Flutter
Hand-written fromJson and toJson methods are easy to read and have no build step, which makes them a good fit for small and medium Flutter apps. A few habits keep them correct as the API evolves.
Tips and common pitfalls
- JSON numbers decode as
intordoubledepending on the value, so cast with(json["price"] as num).toDouble()for fields that may be whole numbers. - Give nullable fields a
?type and handle missing keys; a missing key returnsnullfrom the map lookup. - Decode large responses in a background isolate with
compute()so parsing does not drop frames. - Add a
copyWithmethod when models are used in state management, so you can update one field without rebuilding the whole object.
More questions
Why does my list decode as List<dynamic>?
jsonDecode returns untyped collections. Map each element explicitly, for example (json["tags"] as List).map((e) => e as String).toList().
How do I parse dates?
Store the ISO 8601 string from JSON and convert it with DateTime.parse() in fromJson, and toIso8601String() in toJson.