Background: In development, the server usually returns Json data, which we need to convert to model objects for use. Normally, we use some third-party libraries to dynamically transform models, but there are no Json serialization libraries like Java’s Gson/Jackson libraries in Flutter because runtime reflection is disabled in Flutter. The official interpretation is that run-time reflection interferes with Dart’s Tree shaking. Using Tree shaking to remove unused code in the release can significantly optimize the size of your application. Since reflection is applied to all code by default, tree shaking is difficult to work because it is difficult to know which code is not used when reflection is enabled, and therefore redundant code is difficult to peel off. Dart reflection is disabled in Flutter, and thus dynamic transformation of Model is not possible.

Json_serializable is the jSON-to-model option that dart officially recommends and provides:

  • An automated source code generator to generate JSON serialized data templates for you;
  • Because serialization data code no longer needs to be written or maintained manually, you can minimize the risk of serialization JSON data exceptions at runtime;

Step 1: Add related dependencies

Dependencies include project dependencies and dev_dependencies. Add the following dependencies to pubspec.yaml:

You can refer to github’s official case for configuration, and the latest version can be found in the library (click Search)

  • Note: Need to execute after addingflutter pub getMake sure we have these dependencies in our project.
  • Note: YamL configuration files are very strict about indentation, as shown belowbuild_runnerandjson_serializableIt should be withflutter_testFlat, never write flutter_test after indentation (space), it will consider these two subdirectories of Flutter_test

Step 2: Create a newmodelClass, the referenceJson_serializable 6.1.5

/ / 1. Import import json_annotation. Dart
import 'package:json_annotation/json_annotation.dart';
Json_serializable izable file will be automatically generated after we run the build command, the line may be error before the command is executed
part 'example.g.dart';

//3. This annotation tells the generator that this class is needed to generate the Model class
@JsonSerializable()
class Person {
  /// The generated code assumes these values exist in JSON.
 
   // Explicitly associate JSON field names with Model attributes.
  // Associate the firstName and first_name fields as follows
  @JsonKey(name: "first_name")
  final String firstName;
  final String lastName;
  
  /// The generated code below handles if the corresponding JSON value doesn't
  /// exist or is empty.
  final DateTime? dateOfBirth;

  //4. Necessary constructor
  Person({required this.firstName, required this.lastName, this.dateOfBirth});

  /// Connect the generated [_$PersonFromJson] function to the `fromJson`
  /// factory.
  //5. The corresponding factory constructor must exist
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  /// Connect the generated [_$PersonToJson] function to the `toJson` method.
  //6. The toString method is not required, just used to test data
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}
Copy the code

Step 3: Generate by instructionexample.g.dartfile

part of 'example.dart';

// It takes a map: map 
      
        and maps the values in this map to the entity-like objects we need.
      ,>
// We can use this method to convert the map with json data into the entity-like object we need.
Person _$PersonFromJson(Map<String, dynamic> json) => Person(
      firstName: json['firstName'] as String.lastName: json['lastName'] as String.dateOfBirth: json['dateOfBirth'] = =null
          ? null
          : DateTime.parse(json['dateOfBirth'] as String));// Map the object calling this method directly to a Map based on the field.
// While both methods are private, part lets the two files share scope and namespace, so we need to expose the generated methods to the outside world.
Map<String, dynamic> _$PersonToJson(Person instance) => 
      
       { 'firstName': instance.firstName, 'lastName': instance.lastName, 'dateOfBirth': instance.dateOfBirth? .toIso8601String(), };
      ,>Copy the code
instruction

One-time generation instruction

Run the following command at the project terminal:

flutter  pub run build_runner build
Copy the code
  • This directive is the code that generates the JSON serialization once. This directive goes through our source file and finds the source file that needs to generate the Model class (including the @JsonSerialIZABLE tag) to generate the corresponding.g.date file. It is recommended that you place all Model classes in a separate directory and execute commands from there.

Continuous-generation instruction

If you find it tedious to execute a one-time build instruction every time you change a Model, you can use the following continuous build instruction:

flutter pub run build_runner watch
Copy the code

Running this command in the project root will launch an observer that will monitor changes to files in our project and automatically build the necessary files as needed. Just start the observer once and it runs in the background, which is also safe.

Others (json to Model)

Online generation

  • Open the caijinglong. Making. IO/json2dart/I… Web site

JsonToDart plug-in 【recommended

  • Install the JsonToDart plugin in Android Studio, open Preferences (Mac) or Setting (Window), select Plugins, and search for JsonToDart

Click Install (the above image has been installed), and restart after the installation is complete. If you cannot find it, you can download the local installation from the official website.

Website plugins.jetbrains.com/plugin/1256…

Download the generated files and paste them into the project. Don’t worry about any errors, proceed with G.Art generation and step back to command generation