CodeBlanks Logo Icon CodeBlanks

json_serializable

Learn code generation with json_serializable.

json_serializable

json_serializable is a package that auto-generates fromJson/toJson code. For classes marked with @JsonSerializable(), build_runner generates the code.

Advantage: no hand-written fromJson/toJson; type safe; code updates automatically when fields are added. The generated file has a .g.dart extension.

Usage: add @JsonSerializable() to the class, write the part 'user.g.dart'; directive, run dart run build_runner build.

The part directive and .g.dart

The part 'user.g.dart'; directive includes the generated code into the source file. The .g.dart file is written by build_runner; it is not edited by hand.

The generated file contains _$UserFromJson(m) and _$UserToJson(u) functions. Your class calls them: factory User.fromJson(m) => _$UserFromJson(m);.

When you add a field and run build, the .g.dart updates automatically. No hand-written fromJson/toJson to maintain.

Practice Define an annotation class

Define the annotation class class JsonSerializable { const JsonSerializable(); }. Define class Product { String name; Product(this.name); } marked with @JsonSerializable(). Inside main add print(Product('Kitap').runtimeType);.

Starter code

main.dart
void main() {
  // define the annotation class (const constructor)
  // define a Product class marked with the annotation
  // print the type name of a Product instance
}

Sample solution

main.dart
class JsonSerializable {
  const JsonSerializable();
}

@JsonSerializable()
class Product {
  String name;
  Product(this.name);
}

void main() {
  print(Product('Kitap').runtimeType);
}

Expected output

Product

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add the annotation

Question
@____()
class User {}
Answer
@JsonSerializable()
class User {}

Explanation: @JsonSerializable() marks the class for code generation.

2 json_serializable parts

Term Meaning
@JsonSerializable Annotation
.g.dart Generated file
build_runner Code generator
part Include directive

3 What does json_serializable automate?

  • fromJson/toJson generation Correct answer
  • Database opening
  • HTTP requests
  • UI drawing

Explanation: json_serializable auto-generates fromJson/toJson code.

All lessons in Advanced