Answer
Overview
text
jsonEncodetext
jsonDecodetext
dart:convertjsonEncode — Dart → JSON String
dartimport 'dart:convert'; // Map → JSON string final map = {'name': 'Alice', 'age': 28, 'active': true}; final jsonString = jsonEncode(map); print(jsonString); // {"name":"Alice","age":28,"active":true} print(jsonString.runtimeType); // String // List → JSON string final list = [1, 'two', true, null]; print(jsonEncode(list)); // [1,"two",true,null] // Nested objects final nested = { 'user': {'name': 'Bob', 'scores': [100, 95, 88]}, 'active': true }; print(jsonEncode(nested)); // {"user":{"name":"Bob","scores":[100,95,88]},"active":true}
jsonDecode — JSON String → Dart
dartimport 'dart:convert'; // JSON string → Map final jsonStr = '{"name":"Alice","age":28}'; final decoded = jsonDecode(jsonStr); // dynamic final map = decoded as Map<String, dynamic>; print(map['name']); // Alice print(map['age']); // 28 // JSON array string → List final listStr = '[1, 2, 3]'; final list = jsonDecode(listStr) as List<dynamic>; print(list); // [1, 2, 3]
With Custom Model Classes
dartclass User { final String name; final int age; User({required this.name, required this.age}); // Dart object → Map (used with 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']); } void main() { final user = User(name: 'Alice', age: 28); // Encode: User → JSON string final encoded = jsonEncode(user.toJson()); // '{"name":"Alice","age":28}' // Decode: JSON string → User final decoded = User.fromJson(jsonDecode(encoded)); print(decoded.name); // Alice }
In HTTP Requests
dart// Sending data (encode) await http.post( Uri.parse('https://api.example.com/users'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'name': 'Alice', 'age': 28}), // ← Dart map → JSON string ); // Receiving data (decode) final response = await http.get(Uri.parse('https://api.example.com/users/1')); final user = User.fromJson(jsonDecode(response.body)); // ← JSON string → Dart map
Quick Reference
| Function | Input | Output | Use When |
|---|---|---|---|
text | Dart Map/List/value | JSON text | Sending to API |
text | JSON text | Dart text | Receiving from API |
Memory Trick:
= pack data into a JSON string.textjsonEncode= unpack data out of a JSON string.textjsonDecode