mydomain
No ADS
No ADS

Dart json_serializable

  1. json_serializable
  2. Install the library.
  3. Create model classes
  4. Examples

1. json_serializable

In the Dart ecosystem, converting between Objects and JSON data is a repetitive task. The json_serializable package provides a much more powerful solution than the default dart:convert library. Instead of manually writing hundreds of lines for encoding/decoding, this library uses Code Generation, which minimizes errors and optimizes performance for applications with complex data models.
For small applications, you might consider using the dart:convert library as it is simple and doesn't require any additional configuration.
Or use dart_json_mapper — a library similar to json_serializable:

2. Install the library.

Để sử dụng package json_serializable, bạn cần khai báo các thư viện này trong file pubspec.yaml:
pubspec.yaml
dependencies:
  json_serializable: ^6.11.1
  json_annotation: ^4.9.0

dev_dependencies:
  build_runner: ^2.10.1
See the list of versions:
Import:
import 'package:json_serializable/json_serializable.dart';
import 'package:json_annotation/json_annotation.dart';

3. Create model classes

First, add a build.yaml file to your project. This configuration file instructs build_runner on how to generate new source files from the specified ones.
No ADS
build.yaml
targets:
  $default:
    builders:
      json_serializable:
        generate_for:
          # here should be listed entry point files having 'void main()' function
          - lib/model/model.dart
        options:
          # Options configure how source code is generated for every
          # `@JsonSerializable`-annotated class in the package.
          #
          # The default value for each is listed.
          any_map: false
          checked: false
          constructor: ""
          create_factory: true
          create_to_json: true
          disallow_unrecognized_keys: false
          explicit_to_json: false
          field_rename: none
          generic_argument_factories: false
          ignore_unannotated: false
          include_if_null: true
Next, create the Model classes:
@JsonSerializable
This annotation is used for a class. The json_serializable library will generate code to convert objects of this class to JSON and vice versa
@JsonKey
This optional annotation is used for class properties. It specifies the corresponding JSON property name if it differs from the Dart variable name.
@JsonSerializable()
class Employee {
  @JsonKey(name: 'employeeName') // JSON Property
  String name; 
  String email; // Use default: @JsonKey(name: 'email') 
  Contact contact; // Use default: @JsonKey(name: 'contact')

  @JsonKey(includeFromJson: false)
  String? privateEmail; // This property will be Ignored.
  ..
}  
No ADS
model_file1.dart:
Contains Contact and Employee classes with their respective conversion rules.
lib/model/model_file1.dart
part of 'model.dart';

@JsonSerializable()
class Contact {
  String address;
  String phone;

  Contact(this.address, this.phone); // Constructor

  // IMPORTANT:
  factory Contact.fromJson(Map<String, dynamic> json) =>
      _$ContactFromJson(json);

  // IMPORTANT:
  Map<String, dynamic> toJson() => _$ContactToJson(this);
}

@JsonSerializable()
class Employee {
  @JsonKey(name: 'employeeName') // JSON Property
  String name;
  String email; // Use default: @JsonKey(name: 'email')
  Contact contact; // Use default: @JsonKey(name: 'contact')

  @JsonKey(includeFromJson: false)
  String? privateEmail; // This property will be Ignored.

  Employee(this.name, this.email, this.contact); // Constructor

  // IMPORTANT:
  factory Employee.fromJson(Map<String, dynamic> json) =>
      _$EmployeeFromJson(json);

  // IMPORTANT:
  Map<String, dynamic> toJson() => _$EmployeeToJson(this);
}
model_file2.dart:
Contains the Company class with JSON conversion rules
lib/model/model_file2.dart
part of 'model.dart';

@JsonSerializable()
class Company {
  @JsonKey(name: 'companyName') // JSON Property Name
  String name;

  Contact contact; // Use default: @JsonKey(name: 'contact')

  Company(this.name, this.contact); // Constructor

  // IMPORTANT:
  factory Company.fromJson(Map<String, dynamic> json) =>
      _$CompanyFromJson(json);

  // IMPORTANT:
  Map<String, dynamic> toJson() => _$CompanyToJson(this);
}
  • The part and part of keywords in Dart
lib/model/model.dart
import 'package:json_annotation/json_annotation.dart';

part 'model.g.dart';
part 'model_file1.dart';
part 'model_file2.dart';
build_runner
Open the Terminal window in your IDE:
  • View > Terminal (Visual Studio Code)
  • View > Tool Windows > Terminal (Android Studio)
Run the following command to let build_runner generate the boilerplate code for your Model classes.
dart run build_runner build

# OR:

/Volumes/Apps/Apps/dart-sdk/bin/dart run build_runner build
After successfully running the command, the tool will generate the file "model.g.dart":

4. Examples

This example demonstrates how to convert a Dart object into a JSON data structure.
No ADS
test_dart_to_json_ex1.dart
import 'model/model.dart';

void main() {
  var contact = Contact('Address 1', '12345');
  var employee = Employee('John Smith', 'john@example.com', contact);

  var jsonString = employee.toJson();
  print(jsonString);

  print(' --------------------------- ');

  contact = Contact('Address 1', '99999');
  var company = Company('Google', contact);
  jsonString = contact.toJson();

  print(jsonString);
}
Output:
{employeeName: John Smith, email: john@example.com, contact: Instance of 'Contact'}
 --------------------------- 
{address: Address 1, phone: 99999}

Process finished with exit code 0
Next is an example of converting a JSON text into a Dart object:
test_json_to_dart_ex1.dart
import 'dart:convert';

import 'model/model.dart';

void main() {
  var jsonString1 = '''{
      "employeeName": "John Smith",
      "email": "john@example.com",
      "contact": {
        "address": "Address 1",
        "phone": "12345"
        }
      }''';

  final empMap = jsonDecode(jsonString1) as Map<String, dynamic>;

  var employee = Employee.fromJson(empMap);
  print('Employee Phone: ${employee.contact.phone}');

  print(' --------------------------- ');

  var jsonString2 = '''{
    "companyName": "Google",
    "contact": {
      "address": "Address 1",
      "phone": "99999"
      }
    }''';

  final companyMap = jsonDecode(jsonString2) as Map<String, dynamic>;

  var company = Company.fromJson(companyMap);
  print('Company Phone: ${company.contact.phone}');
}
Output:
Employee Phone: 12345
 --------------------------- 
Company Phone: 99999
No ADS
No ADS