Mastering JSON Serialization in Flutter: A Comprehensive Guide
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, and it is also easy for machines to parse and generate.
JSON is often used to transmit data between a server and a client, or to store data in a file.
In Flutter, JSON serialization is the process of converting a Dart object to a JSON string, and JSON deserialization is the process of converting a JSON string to a Dart object.
There are two ways to do JSON serialization and deserialization in Flutter:
- Manual serialization
In manual serialization, you manually write the code to convert a Dart object to a JSON string, and vice versa. This is the simplest way to do JSON serialization, but it can be time-consuming and error-prone, especially for complex data structures.
- Automatic serialization
In automatic serialization, you use a library to generate the code for converting a Dart object to a JSON string, and vice versa. This is a more efficient and less error-prone approach, but it requires you to use a library.
One popular library for automatic JSON serialization in Flutter is the json_serializable package. This package provides annotations that you can use to annotate your Dart classes.
The annotations tell the library how to generate the code for converting your classes to and from JSON.
dependencies:
flutter:
sdk: flutter
json_annotation: ^4.0.0 # Use the latest version of json_annotation
dev_dependencies:
build_runner: ^1.1.0
json_serializable: ^4.5.0 # Use the latest version of json_serializable
..
json_annotation: This package provides the @JsonSerializable annotation for annotating your Dart data classes.
json_serializable: This package works alongside build_runner to generate serialization and deserialization code for your annotated classes.
- You need to run flutter pub get to fetch the updated dependencies.
Step 1:
Create a Dart Data Class:
import 'package:json_annotation/json_annotation.dart';
part 'person.g.dart';
/// This class represents a person.
@JsonSerializable()
class Person {
/// The person's name.
final String name;
/// The person's age.
final int age;
/// Constructs a new person.
Person(this.name, this.age);
/// Creates a person from a JSON map.
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
/// Converts the person to a JSON map.
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
..
Step 2:
Generate Serialization Code:
flutter pub run build_runner build
..
Step 3: How to use?
Deserializing JSON to a Dart object and serializing a Dart object to JSON in your Flutter application:
import 'person.g.dart'; // Import the generated file
void main() {
final json = '{"name": "John", "age": 30}';
// Deserialize JSON to a Dart Object
final person = Person.fromJson(jsonDecode(json));
print(person.name); // Output: John
print(person.age); // Output: 30
// Serialize a Dart Object to JSON
final newPerson = Person('Alice', 25);
final serializedJson = jsonEncode(newPerson.toJson());
print(serializedJson); // Output: {"name":"Alice","age":25}
}
..
The best choice for you will depend on your specific needs. If you need to work with complex data structures and you want to save time and effort, then json_serializable is a good choice.
If you are working with simple data structures and you want the flexibility to define your Dart classes in any way you want, then a plugin is a good choice.
JsonToDart (JSON To Dart) - Android studio Plugin https://plugins.jetbrains.com/plugin/12562-jsontodart-json-to-dart-
Doc
https://docs.flutter.dev/data-and-backend/serialization/json#manual-encoding
Others:
Paste your JSON in the textarea below, click convert and get your Dart classes for free.
https://javiercbk.github.io/json_to_dart/
https://app.quicktype.io/?l=dart
Overview:
JSON serialization is the process of converting data from a Dart object to a JSON string (serialization) and vice versa (deserialization). In Flutter, JSON serialization is crucial when working with APIs, as it allows developers to easily send and receive structured data in a format that can be understood by both the client and server
Comments
Post a Comment