JSON ➜ Dart Model Converter
JSON ➜ Dart Complete Guide
JSON is the most common way to send data between servers and Flutter apps. Dart provides built-in tools to convert JSON into Dart objects and back to JSON again. This guide explains how to convert JSON to Dart models and how to use them in real Flutter projects.
What is JSON ➜ Dart Conversion?
JSON to Dart conversion lets you map JSON data into Dart model classes. This gives you:
- type safety
- autocompletion in IDE
- easier debugging
- cleaner API handling
Example JSON Data
{
"id": 5,
"name": "John Doe",
"email": "john@example.com",
"isActive": true
}How to Parse JSON in Dart
Use dart:convert to decode JSON.
import 'dart:convert';
void main() {
const jsonString = '{"id":1,"name":"Alice"}';
final data = jsonDecode(jsonString);
print(data['name']); // Alice
}Create Dart Model Class
class User {
final int id;
final String name;
final String email;
User({
required this.id,
required this.name,
required this.email,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"name": name,
"email": email,
};
}
}How to Parse JSON List in Dart
final jsonString = '[{"id":1,"name":"A"},{"id":2,"name":"B"}]';
final List<dynamic> decoded = jsonDecode(jsonString);
final users = decoded.map((u) => User.fromJson(u)).toList();How to Read JSON File in Dart
import 'dart:convert';
import 'dart:io';
void main() async {
final file = File('assets/user.json');
final contents = await file.readAsString();
final data = jsonDecode(contents);
print(data);
}In Flutter, put files inside assets/and add them in pubspec.yaml.
FAQ
Do I need packages to parse JSON?
No. Dart already supports JSON parsing using dart:convert.
What about complex/nested JSON?
Create nested model classes and call childModel.fromJson().
What is the best practice?
- use model classes
- avoid dynamic everywhere
- enable null safety
How do I handle null fields?
Use nullable types like String?.