Mastering JSON Serialization in Flutter | How To Serialize JSON in Flutter Effectively.

Explore the art of JSON serialization in Flutter with our in-depth guide. 

Learn essential techniques and best practices for efficient JSON data handling in your Flutter projects.


Encoding and serialization are the same thing— is the process of converting data structures (like objects or lists) into a format that can be stored or transmitted, such as JSON strings. 

Decoding and deserialization are the opposite process—is the reverse process, converting that format back into usable data structures.

Assuming you have the following JSON data:


{
  "name": "John Doe",
  "email": "john.doe@example.com"
}



Follow these steps to create Dart data classes using json_serializable:


Step 1: 📦Add the following dependencies

Run the following commands to add the dependencies to your pubspec.yaml file:

  • dart pub add json_annotation
  • dart pub add dev:json_serializable
  • dart pub add dev:build_runner

Run flutter pub get to fetch the dependencies.


Use:

  • json_annotation : It allows you to annotate your Dart classes with @JsonSerializable() to indicate how the serialization/deserialization should be handled.
  • json_serializable: It generates the necessary serialization/deserialization code based on the annotations you added to your Dart classes.
  • build_runner: It's often used with json_serializable to automatically generate serialization/deserialization code during development.
  • pub get: This command will download and fetch the dependencies specified in your pubspec.yaml

..



Step 2: Create Data Class 🧱:

  • Create a Dart file for your data class (e.g., users.dart).
  • Annotate the class with @JsonSerializable().
  • Generate JSON response to data class (https://app.quicktype.io/)


import 'package:json_annotation/json_annotation.dart'; // add this import for json annotation
part 'users.g.dart'; // auto-generated file will create in this file name

@JsonSerializable()
class Users {
  @JsonKey(name: "name")
  String name;
  @JsonKey(name: "email")
  String email;

  Users({
    required this.name,
    required this.email,
  });

  factory Users.fromJson(Map json) => _$UsersFromJson(json);

  Map toJson() => _$UsersToJson(this);
}


Do not worry about error

..



Step 3: 🏗️ Run Code Generation : 

Run the build process to generate the serialization/deserialization code.

  • dart run build_runner build





Usage in Your Code 🚀:
Use the generated Users class for serialization and deserialization in your main Dart file.


import 'package:seat/my_model/users.dart';

void main() {
  // Decoding and deserialization are the reverse process —
  // converting that format back into usable data structures.

  // Example Data Structure: How the JSON data looks like
  Map<String, dynamic> jsonData = {
    "name": "prouix",
    "email": "prouixdev@gmail.com"
  };

  // 🔄 Deserialization: Converting JSON data to a Dart object or data structure (such as Users)
  Users user = Users.fromJson(jsonData);

  // Print the deserialized object
  print('Deserialized User:');
  print('Name: ${user.name}');
  print('Email: ${user.email}');


  //..............................................................................
  // Encoding and serialization are the same process — converting data structures (like objects or lists)
  // into a format that can be stored or transmitted, such as JSON strings.

  // 🔄 Serialization: Converting 'user' Dart object or data structure to a JSON representation 'jsonUser'.
  Map<String, dynamic> jsonUser = user.toJson();

  // Print the serialized JSON
  print('\nSerialized JSON:');
  print(jsonUser);
}



Benefits:

Code Generation 🏗️:

  • Automated code generation reduces boilerplate code.
  • Generated code is optimized for performance.

Type Safety 🛡️:

  • Type-safe code prevents runtime errors.

Consistency Across Codebase 🤝:

  • Ensures consistency in serialization/deserialization.




Notes:

Annotations in programming languages, including Dart, are a form of metadata that provides additional information about the code they annotate. 

They are used to convey instructions or metadata to tools, frameworks, or other code processors. In Dart, annotations are prefixed with the @ symbol.

Annotation Purpose and Use
@JsonSerializable() Generates JSON serialization/deserialization code for the annotated class using json_serializable.
@JsonKey(name: "name") Customizes the serialization/deserialization process for the name field, specifying the JSON key as "name".

eg: @JsonKey(name: "user_name") // Customize the serialization/deserialization for the user_name field
final String userName;

..

..

Ref

https://docs.flutter.dev/data-and-backend/serialization/json

Comments