JSON Serialization in Dart for Flutter
JSON serialization is the process of converting Dart objects into JSON format and vice versa. This is essential in Flutter apps because most APIs and network services communicate using JSON. By serializing and deserializing data, you can easily send and receive structured information between your app and backend services. Clean and reliable JSON handling is critical for scalable, maintainable Flutter code.
Always check for the presence and type of fields in your JSON data to avoid runtime errors. Defensive parsing ensures your Flutter app remains robust even when backend data changes or is incomplete.
main.dart
123456789101112131415161718192021222324252627282930313233class User { final String name; final int age; User({required this.name, required this.age}); // Deserialize from JSON factory User.fromJson(Map<String, dynamic> json) { return User( name: json['name'] as String, age: json['age'] as int, ); } // Serialize to JSON Map<String, dynamic> toJson() { return { 'name': name, 'age': age, }; } } void main() { // Example: Serialize User user = User(name: 'Alice', age: 30); Map<String, dynamic> json = user.toJson(); print(json); // Example: Deserialize User anotherUser = User.fromJson({'name': 'Bob', 'age': 25}); print('${anotherUser.name}, ${anotherUser.age}'); }
When working with JSON from network sources, you may encounter null or missing fields. Dart's null safety helps, but you should always handle these cases explicitly. Use default values or null-aware operators to avoid runtime errors when fields are absent or have unexpected types.
main.dart
1234567891011121314151617181920212223242526272829303132333435363738import 'package:flutter/material.dart'; class Product { final String title; final double price; Product({required this.title, required this.price}); factory Product.fromJson(Map<String, dynamic> json) { return Product( title: json['title'] as String? ?? 'Unknown', price: (json['price'] is num) ? (json['price'] as num).toDouble() : 0.0, ); } } class ProductWidget extends StatelessWidget { final Map<String, dynamic> jsonData; const ProductWidget({super.key, required this.jsonData}); @override Widget build(BuildContext context) { final product = Product.fromJson(jsonData); return ListTile( title: Text(product.title), subtitle: Text('Price: \$${product.price}'), ); } } void main() { runApp(MaterialApp( home: Scaffold( body: ProductWidget(jsonData: {'title': null, 'price': 'not a number'}), ), )); }
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Can you give an example of how to serialize and deserialize a Dart object?
What are some best practices for handling missing or null fields in JSON?
How does Dart's null safety feature help with JSON parsing?
Mahtavaa!
Completion arvosana parantunut arvoon 7.14
JSON Serialization in Dart for Flutter
Pyyhkäise näyttääksesi valikon
JSON serialization is the process of converting Dart objects into JSON format and vice versa. This is essential in Flutter apps because most APIs and network services communicate using JSON. By serializing and deserializing data, you can easily send and receive structured information between your app and backend services. Clean and reliable JSON handling is critical for scalable, maintainable Flutter code.
Always check for the presence and type of fields in your JSON data to avoid runtime errors. Defensive parsing ensures your Flutter app remains robust even when backend data changes or is incomplete.
main.dart
123456789101112131415161718192021222324252627282930313233class User { final String name; final int age; User({required this.name, required this.age}); // Deserialize from JSON factory User.fromJson(Map<String, dynamic> json) { return User( name: json['name'] as String, age: json['age'] as int, ); } // Serialize to JSON Map<String, dynamic> toJson() { return { 'name': name, 'age': age, }; } } void main() { // Example: Serialize User user = User(name: 'Alice', age: 30); Map<String, dynamic> json = user.toJson(); print(json); // Example: Deserialize User anotherUser = User.fromJson({'name': 'Bob', 'age': 25}); print('${anotherUser.name}, ${anotherUser.age}'); }
When working with JSON from network sources, you may encounter null or missing fields. Dart's null safety helps, but you should always handle these cases explicitly. Use default values or null-aware operators to avoid runtime errors when fields are absent or have unexpected types.
main.dart
1234567891011121314151617181920212223242526272829303132333435363738import 'package:flutter/material.dart'; class Product { final String title; final double price; Product({required this.title, required this.price}); factory Product.fromJson(Map<String, dynamic> json) { return Product( title: json['title'] as String? ?? 'Unknown', price: (json['price'] is num) ? (json['price'] as num).toDouble() : 0.0, ); } } class ProductWidget extends StatelessWidget { final Map<String, dynamic> jsonData; const ProductWidget({super.key, required this.jsonData}); @override Widget build(BuildContext context) { final product = Product.fromJson(jsonData); return ListTile( title: Text(product.title), subtitle: Text('Price: \$${product.price}'), ); } } void main() { runApp(MaterialApp( home: Scaffold( body: ProductWidget(jsonData: {'title': null, 'price': 'not a number'}), ), )); }
Kiitos palautteestasi!