JSON in Dart & Flutter — jsonDecode, jsonEncode & Null Safety
Dart's dart:convert library provides jsonDecode() and jsonEncode() for JSON parsing. For Flutter apps, the community pattern is to add fromJson/toJson factory methods to your model classes, with optional code generation via json_serializable.
Parse JSON with jsonDecode
jsonDecode() from dart:convert parses a JSON string into a dynamic Dart object — a Map<String, dynamic> for objects, or a List<dynamic> for arrays.
import 'dart:convert';
void main() {
final String jsonString = '{"id":1,"name":"Alice","email":"alice@example.com"}';
final Map<String, dynamic> data = jsonDecode(jsonString);
print(data['name']); // Alice
print(data['id']); // 1
}Encode to JSON with jsonEncode
jsonEncode() converts a Dart Map, List, String, int, double, bool, or null to a JSON string.
import 'dart:convert';
void main() {
final data = {
'name': 'Alice',
'scores': [95, 87, 92],
'active': true,
};
final String json = jsonEncode(data);
print(json);
// {"name":"Alice","scores":[95,87,92],"active":true}
}Model class with fromJson and toJson
The standard Flutter pattern is to add a named constructor fromJson(Map<String, dynamic>) and a toJson() method to your 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'] as int,
name: json['name'] as String,
email: json['email'] as String,
);
}
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'email': email,
};
}
// Usage
final user = User.fromJson(jsonDecode(jsonString));
final backToJson = jsonEncode(user.toJson());Handle null safety
With Dart null safety, use nullable types and the ?? operator to provide defaults for missing or null JSON fields.
class Profile {
final int id;
final String? bio; // nullable — may be absent
final String website; // non-nullable — provide a default
Profile({required this.id, this.bio, required this.website});
factory Profile.fromJson(Map<String, dynamic> json) {
return Profile(
id: json['id'] as int,
bio: json['bio'] as String?,
website: json['website'] as String? ?? '',
);
}
}Decode a JSON list (Flutter API response)
A common Flutter pattern for decoding a JSON array from an HTTP response.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) {
final List<dynamic> list = jsonDecode(response.body);
return list.map((json) => User.fromJson(json)).toList();
}
throw Exception('Failed to load users');
}Related Tools
Frequently Asked Questions
How do I parse JSON in Dart?▾
Import dart:convert and call jsonDecode(jsonString). It returns a dynamic value — cast to Map<String, dynamic> for a JSON object or List<dynamic> for a JSON array.
How do I convert a Dart object to JSON?▾
Call jsonEncode(value) from dart:convert. The value must be a Map, List, String, int, double, bool, or null. For custom classes, implement a toJson() method that returns a Map<String, dynamic> and pass the result to jsonEncode.
How do I handle missing or null JSON fields in Dart with null safety?▾
Declare the property as a nullable type (String?, int?). In fromJson, cast with as String? and use ?? to provide a fallback: json['key'] as String? ?? 'default'.
What is json_serializable in Flutter?▾
json_serializable is a code-generation package that auto-generates fromJson/toJson methods. Annotate your class with @JsonSerializable() and run dart run build_runner build to generate the boilerplate.
How do I decode a JSON array from a Flutter HTTP response?▾
After getting the response body, call jsonDecode(response.body) which returns a List<dynamic>. Then map over it: (list as List).map((e) => MyModel.fromJson(e)).toList().
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →If jsondecode.com saved you time, share it with your team
Free forever. No ads. No sign-up. Help other developers find it.