Introduction to JSON annotations
Installing and Using json_serializable and json_annotation packages
Add this to your package's pubspec.yaml file:
# pubspec.yaml
dependencies:
json_annotation: ^4.0.0
dev_dependencies:
build_runner:
json_serializable 4.0.2
You can then install packages from the command line:
Alternatively, your editor might support dart pub get
. Check the docs for your editor to learn more.
Example
Now you can use it in your Dart code by importing it like this:
import 'package:json_annotation/json_annotation.dart';
part 'my_model.g.dart';
Note that the line partmy_demo.g.dart
will give you a warning, because the file is not created yet
Write the following code
import 'package:json_annotation/json_annotation.dart';
part 'my_model.g.dart';
@freezed
class Person with _$Person {
const factory Person({
@required String firstName,
@required String lastName,
}) = _Person;
factory Person.fromJson(Map<String, dynamic> json) =>
_$PersonFromJson(json);
}
To generate the code type the following command
$ flutter pub run build_runner build
Ignore lint warnings on generated files
It is likely that the code generated by Json_Serializer will cause your linter to report warnings.
The solution to this problem is to tell the linter to ignore generated files, by modifying your analysis_options.yaml
:
analyzer:
exclude:
- "**/*.g.dart"