
5:46
Flutter Tutorial - Convert JSON To Object & Object To JSON | JSON Serializable
HeyFlutter․com
Overview
This video demonstrates how to use the `json_serializable` package in Flutter to automatically generate `toJson` and `fromJson` methods for Dart model classes. This process eliminates the need for manual creation of these methods, saving significant development time. The tutorial covers installing the package, configuring `pubspec.yaml`, annotating model classes, and running the build runner command to generate the necessary serialization code. It also explains how to handle nested objects within model classes.
How was this?
Save this permanently with flashcards, quizzes, and AI chat
Chapters
- Manually creating `toJson` and `fromJson` methods for every model class in Flutter is time-consuming.
- The `json_serializable` package automates this process, generating these methods automatically.
- This tutorial will guide you through installing and using the package.
Understanding automated JSON serialization is crucial for efficient data handling in Flutter apps, especially when dealing with APIs and local storage.
- Add `json_annotation` to your project's `dependencies` in `pubspec.yaml`.
- Include `build_runner` and `json_serializable` in your `dev_dependencies`.
- After adding dependencies, run `flutter pub get` to install them.
Correctly setting up the necessary dependencies is the first step to enabling the code generation features for JSON serialization.
Pasting the dependency lines for `json_annotation`, `build_runner`, and `json_serializable` into the `pubspec.yaml` file.
- Annotate each model class that needs JSON serialization with `@JsonSerializable()`.
- Import the `json_annotation.dart` library at the top of your model file.
- Add a factory constructor named `_$ClassNameFromJson(Map<String, dynamic> json)` and a method named `Map<String, dynamic> toJson()` to your class.
- A generated file with the suffix `.g.dart` will be created, containing the actual serialization logic.
These annotations and factory constructors tell the `build_runner` which classes to process and how to generate the serialization code.
Adding `@JsonSerializable()` above a `Person` class and importing `package:json_annotation/json_annotation.dart`.
- Open your terminal in the root directory of your Flutter project.
- Run the command `flutter pub run build_runner build`.
- This command will scan your project for annotated classes and generate the corresponding `.g.dart` files.
- After generation, any errors related to manual `toJson`/`fromJson` methods should disappear.
This build step is what actually creates the efficient serialization and deserialization code, making your models ready to be converted to and from JSON.
Executing `flutter pub run build_runner build` in the terminal and observing the creation of `person.g.dart`.
- In your application code, you can now use the generated `Person.fromJson(jsonMap)` and `personObject.toJson()` methods.
- If you modify your model class (e.g., add or remove fields), you must re-run the `flutter pub run build_runner build` command.
- This ensures that the generated serialization code stays synchronized with your model's structure.
Regularly regenerating the serialization code after model changes is essential to prevent runtime errors and maintain data integrity.
Calling `Person.fromJson(jsonMap)` to create an object from JSON and `personObject.toJson()` to convert an object back to a JSON map.
- To serialize nested objects (e.g., an `Address` object within a `Person` object), the nested class must also be annotated with `@JsonSerializable()`.
- In the parent class (`Person`), you need to add `explicitToJson: true` to the `@JsonSerializable()` annotation.
- This ensures that the `toJson` and `fromJson` methods are generated for the nested class as well.
Properly configuring nested objects ensures that complex data structures can be serialized and deserialized correctly, maintaining relationships between data.
Adding `explicitToJson: true` to `@JsonSerializable()` in the `Person` class when it contains an `Address` object, and ensuring `Address` is also annotated.
Key takeaways
- Automate JSON serialization in Flutter using `json_serializable` to save development time.
- Configure `pubspec.yaml` with `json_annotation` and `build_runner` for code generation.
- Annotate model classes with `@JsonSerializable()` and import `json_annotation.dart`.
- Run `flutter pub run build_runner build` to generate `toJson` and `fromJson` methods.
- Re-run the build command whenever model classes are modified.
- Use `explicitToJson: true` in the parent class annotation to handle nested model objects.
- Always save your model files before running the build command to ensure changes are recognized.
Key terms
JSON SerializationDeserializationjson_serializablejson_annotationbuild_runnerpubspec.yamlModel ClasstoJsonfromJsonNested ObjectsexplicitToJson
Test your understanding
- What is the primary benefit of using the `json_serializable` package in Flutter?
- How do you add the `json_serializable` package and its dependencies to a Flutter project?
- What steps are required within a Dart model class to prepare it for code generation by `json_serializable`?
- What command do you execute in the terminal to generate the `toJson` and `fromJson` methods?
- Why is it necessary to re-run the build command after modifying a model class, and how does this relate to nested objects?