Answer
Overview
text
jsonEncodetext
jsonDecodetext
dart:convertjsonEncode — Dart Object → JSON String
dartimport 'dart:convert'; // Map to JSON string final user = {'name': 'Alice', 'age': 28, 'isActive': true}; final jsonString = jsonEncode(user); print(jsonString); // {"name":"Alice","age":28,"isActive":true} // List to JSON string final items = [1, 'hello', true, null]; print(jsonEncode(items)); // [1,"hello",true,null]
jsonDecode — JSON String → Dart Object
dartimport 'dart:convert'; final jsonString = '{"name":"Alice","age":28,"isActive":true}'; // Returns dynamic — usually a Map or List final Map<String, dynamic> user = jsonDecode(jsonString); print(user['name']); // Alice print(user['age']); // 28 // Decoding a JSON array final listString = '[1, 2, 3, 4]'; final List<dynamic> numbers = jsonDecode(listString); print(numbers); // [1, 2, 3, 4]
With HTTP API Response
dartimport 'package:http/http.dart' as http; import 'dart:convert'; Future<User> fetchUser(int id) async { final response = await http.get( Uri.parse('https://api.example.com/users/$id'), ); if (response.statusCode == 200) { // response.body is a String → decode it to Map final Map<String, dynamic> data = jsonDecode(response.body); return User.fromJson(data); } throw Exception('Failed to load user'); } // Sending data — encode Dart map to JSON string Future<void> createUser(User user) async { await http.post( Uri.parse('https://api.example.com/users'), headers: {'Content-Type': 'application/json'}, body: jsonEncode(user.toJson()), // Map → JSON string for request body ); }
Comparison Table
| Feature | text | text |
|---|---|---|
| Direction | Dart → JSON String | JSON String → Dart |
| Input | Map, List, String, num, bool, null | JSON String |
| Output | text | text |
| Use case | Sending data to API (request body) | Receiving data from API (response body) |
Custom Object Serialization
dartclass User { final String name; final int age; User({required this.name, required this.age}); // Dart object → Map (for jsonEncode) Map<String, dynamic> toJson() => {'name': name, 'age': age}; // Map (from jsonDecode) → Dart object factory User.fromJson(Map<String, dynamic> json) => User(name: json['name'], age: json['age']); } // Full round-trip final user = User(name: 'Alice', age: 28); final encoded = jsonEncode(user.toJson()); // '{"name":"Alice","age":28}' final decoded = User.fromJson(jsonDecode(encoded)); // User object
Memory Aid:
→ Encode = Pack into a string (send it away)textjsonEncode → Decode = Unpack from a string (read it in)textjsonDecode