o7planning

Dart dart_json_mapper Tutorial with Examples

  1. dart_json_mapper
  2. Install the library
  3. Example

1. dart_json_mapper

dart_json_mapper is a library that provides a better solution than dart:convert for working with JSON data. It is suitable for applications with complex JSON models. However, to use it you need a few configuration steps. For small applications you should use the dart:convert library - it's simple and doesn't need any additional configuration.
The dart_json_mapper library inspired by json2typescript, serde, gson, feature parity with Java Jackson is very popular and has only four Annotations to remember to cover all possible use cases.
dart_json_mapper vs json_serializable
json_serializable is a better JSON handling library than dart:convert. However, it is only a semi-automatic library, and cannot be compared with the features that dart_json_mapper offers.

2. Install the library

To use the dart_json_mapper library, you need to declare it in the pubspec.yaml file:
pubspec.yaml
dependencies:
  dart_json_mapper:

dev_dependencies:
  build_runner:

3. Example

First, add the build.yaml file to your project. This is the configuration file, used to instruct build_runner to generate new source code files from the specified source code files.
build.yaml
targets:
  $default:
    builders:
      dart_json_mapper:
        generate_for:
        # here should be listed entry point files having 'void main()' function
          - lib/src/model_file1.dart
          - lib/src/model_file2.dart

      # This part is needed to tell original reflectable builder to stay away
      # it overrides default options for reflectable builder to an **empty** set of files
      reflectable:
        generate_for:
          - no/files
Next, create 2 files in the "lib/src" directory. Files placed in this directory are only used internally by your project. If you want them to be usable in other projects, put them in the "lib" folder.
dart_json_mapper_tutorial (Your Project Name)
  - lib
      - src
           - model_file1.dart
           - model_file2.dart
model_file1.dart: Contains the Contact and Employee classes, with rules for converting them to JSON structures and vice versa.
lib/src/model_file1.dart
import 'package:dart_json_mapper/dart_json_mapper.dart'
    show JsonMapper, jsonSerializable, JsonProperty;

@jsonSerializable
class Contact {
  String address;
  String phone;
  Contact(this.address, this.phone); // Constructor
}
@jsonSerializable
class Employee {
  @JsonProperty(name: 'employeeName')
  String name;
  String email;
  Contact contact;
  Employee(this.name, this.email, this.contact); // Constructor
}
void main() {
  // Empty
}
model_file2.dart: Contains the Company class, with rules for converting it to JSON structures and vice versa.
lib/src/model_file2.dart
import 'package:dart_json_mapper/dart_json_mapper.dart'
    show JsonMapper, jsonSerializable, JsonProperty;

import 'model_file1.dart';

@jsonSerializable
class Company {
  @JsonProperty(name: 'companyName')
  String name;
  Contact contact;
  Company(this.name, this.contact); // Constructor
}
void main() {
  // Empty
}
Open a Terminal window on the IDE:
  • View > Terminal (Visual Studio Code)
  • View > Tool Windows > Terminal (Android Studio)
Run one of the two commands below (Depending on whether your project is Dart or Flutter):
dart pub run build_runner build --delete-conflicting-outputs

flutter pub run build_runner build --delete-conflicting-outputs
As a result, 2 files will be created. Run the above command again if you change the source code on the model files.
Create an example "bin/test_ex1.dart", which shows you how to convert a Dart object to JSON text:
bin/test_ex1.dart
import 'package:dart_json_mapper/dart_json_mapper.dart'
    show JsonMapper, jsonSerializable, JsonProperty;

// 'dart_json_mapper_tutorial' : Your project name.
import 'package:dart_json_mapper_tutorial/src/model_file1.dart';
import 'package:dart_json_mapper_tutorial/src/model_file2.dart';

import 'package:dart_json_mapper_tutorial/src/model_file1.mapper.g.dart'
    as modelFile1;
import 'package:dart_json_mapper_tutorial/src/model_file2.mapper.g.dart'
    as modelFile2;

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

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

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

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

  print(jsonString);
}
Output:
{
 "employeeName": "John Smith",
 "email": "john@example.com",
 "contact": {
  "address": "Address 1",
  "phone": "12345"
 }
}
 ---------------------------
{
 "companyName": "Google",
 "contact": {
  "address": "Address 1",
  "phone": "99999"
 }
}
Next is an example that converts a JSON text to a Dart object:
bin/test_ex2.dart
import 'package:dart_json_mapper/dart_json_mapper.dart'
    show JsonMapper, jsonSerializable, JsonProperty;

// 'dart_json_mapper_tutorial' : Your project name.
import 'package:dart_json_mapper_tutorial/src/model_file1.dart';
import 'package:dart_json_mapper_tutorial/src/model_file2.dart';

import 'package:dart_json_mapper_tutorial/src/model_file1.mapper.g.dart'
    as modelFile1;
import 'package:dart_json_mapper_tutorial/src/model_file2.mapper.g.dart'
    as modelFile2;

void main() {
  var jsonString1 = '''{
      "employeeName": "John Smith",
      "email": "john@example.com",
      "contact": {
        "address": "Address 1",
        "phone": "12345"
        }
      }''';
  modelFile1.initializeJsonMapper();
  // May be null:
  var employee = JsonMapper.fromJson<Employee>(jsonString1);
  print('Employee Phone: ${employee!.contact.phone}');

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

  modelFile2.initializeJsonMapper();
  var jsonString2 = '''{
    "companyName": "Google",
    "contact": {
      "address": "Address 1",
      "phone": "99999"
      }
    }''';
  // May be null:
  var company = JsonMapper.fromJson<Company>(jsonString2);
  print('Company Phone: ${company!.contact.phone}');
}
Output:
Employee Phone: 12345
 ---------------------------
Company Phone: 99999