التحليل المباشر
import 'dart:convert';
final data = jsonDecode(response.body);
print(data["title"]); // map
print(data[0]["name"]); // list of maps
تحويل لنموذج (الأفضل)
عرّف صنفًا بدالة fromJson:
class Post {
final int id;
final String title;
Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json["id"],
title: json["title"],
);
}
}
الاستخدام
Future<List<Post>> fetchPosts() async {
final response = await http.get(uri);
final List data = jsonDecode(response.body);
return data.map((json) => Post.fromJson(json)).toList();
}
toJson للإرسال
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
};
💡 تحويل JSON لنماذج Dart يعطيك أمان النوع وإكمالًا تلقائيًّا وكودًا أنظف.
🎯 التالي: البرمجة غير المتزامنة.