· Flutter Deep Dives · 2 min read

JSON serialization in Flutter with JSON Serializable package

The json_serializable package generates the necessary code for converting your Dart objects to JSON and vice versa. In order to use this package, follow the steps below:

  1. Add the json_serializable package to your project’s dependencies in the pubspec.yaml file:
dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^4.4.0
  json_serializable: ^4.1.4
  1. Run flutter pub get to download the dependencies.

  2. Create a Dart class that represents your data model. For example, let’s say we have a User class:

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  final String name;
  final int age;

  User(this.name, this.age);

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);
}
  1. Run the build_runner command to generate the necessary serialization code:
flutter pub run build_runner build
  1. The code generation step will generate two files: user.g.dart and user.toJson.dart. The user.g.dart file contains the JSON serialization and deserialization code. You don’t need to modify this file, as it is generated by the json_serializable package.

  2. Now you can easily convert your User object to JSON or vice versa using the generated methods. Here’s an example:

void main() {
  final user = User('John Doe', 25);

  // Converting object to JSON
  final json = user.toJson();
  print(json); // Output: {"name":"John Doe","age":25}

  // Converting JSON to object
  final userFromJson = User.fromJson(json);
  print(userFromJson.name); // Output: John Doe
  print(userFromJson.age); // Output: 25
}

By utilizing the json_serializable package in Flutter, you can easily handle JSON serialization and deserialization, reducing the amount of manual coding required. This package also saves you time and prevents mistakes when working with JSON data.

#Flutter #JSONSerialization

Share:
Back to Blog