json_serializable 6.2.0
json_serializable: ^6.2.0 copied to clipboard
Automatically generate code for converting to and from JSON by annotating Dart classes.
Provides Dart Build System builders for handling JSON.
The builders generate code when they find members annotated with classes defined in package:json_annotation.
-
To generate to/from JSON code for a class, annotate it with
JsonSerializable. You can provide arguments toJsonSerializableto configure the generated code. You can also customize individual fields by annotating them withJsonKeyand providing custom arguments. See the table below for details on the annotation values. -
To generate a Dart field with the contents of a file containing JSON, use the
JsonLiteralannotation.
Setup #
To configure your project for the latest released version of
json_serializable, see the example.
Example #
Given a library example.dart with an Person class annotated with
JsonSerializable:
import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';
@JsonSerializable()
class Person {
/// The generated code assumes these values exist in JSON.
final String firstName, lastName;
/// The generated code below handles if the corresponding JSON value doesn't
/// exist or is empty.
final DateTime? dateOfBirth;
Person({required this.firstName, required this.lastName, this.dateOfBirth});
/// Connect the generated [_$PersonFromJson] function to the `fromJson`
/// factory.
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
/// Connect the generated [_$PersonToJson] function to the `toJson` method.
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
Building creates the corresponding part example.g.dart:
part of 'example.dart';
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<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
'firstName': instance.firstName,
'lastName': instance.lastName,
'dateOfBirth': instance.dateOfBirth?.toIso8601String(),
};
Running the code generator #
Once you have added the annotations to your code you then need to run the code
generator to generate the missing .g.dart generated dart files.
With a Dart package, run dart run build_runner build in the package directory.
With a Flutter package, run flutter pub run build_runner build in your package
directory.
Annotation values #
The only annotation required to use this package is JsonSerializable. When
applied to a class (in a correctly configured package), toJson and fromJson
code will be generated when you build. There are three ways to control how code
is generated:
- Setting properties on
JsonKeyannotating the target field. - Set properties on
JsonSerializableannotating the target type. - Add configuration to
build.yaml– see below.
Every JsonSerializable field is configurable via build.yaml. If you find
you want all or most of your classes with the same configuration, it may be
easier to specify values once in the YAML file. Values set explicitly on
JsonSerializable take precedence over settings in build.yaml.
There is some overlap between settings on JsonKey and
JsonSerializable. In these cases, the property on JsonKey takes
precedence over any value set on JsonSerializable.
Enums #
Annotate enum types with JsonEnum (new in json_annotation 4.2.0) to:
- Specify the default rename logic for each enum value using
fieldRename. For instance, usefieldRename: FieldRename.kebabto encodeenumvaluenoGoodas"no-good". - Force the generation of the
enumhelpers, even if theenumis not referenced in code. This is an edge scenario, but useful for some.
Annotate enum values with JsonValue to specify the encoded value to map
to target enum entries. Values can be of type String or int.
enum StatusCode {
@JsonValue(200)
success,
@JsonValue('500')
weird,
}
Supported types #
Out of the box, json_serializable supports many common types in the
dart:core
library:
BigInt, bool, DateTime, double, Duration, Enum, int,
Iterable, List, Map, num, Object, Set, String,
Uri
The collection types –
Iterable, List, Map, Set
– can contain values of all the above types.
For Map, the key value must be one of
BigInt, DateTime, Enum, int, Object, String, Uri
Custom types and custom encoding #
If you want to use types that are not supported out-of-the-box or if you want to customize the encoding/decoding of any type, you have a few options.
- If you own/cotrol the desired type, add a
fromJsonconstructor and/or atoJson()function to the type. Note: while you can usejson_serializablefor these types, you don't have to! The generator code only looks for these methods. It doesn't care how they were created. - Use the
JsonKey.toJsonandJsonKey.fromJsonproperties to specify custom conversions on the annotated field. The functions specified must be top-level or static. See the documentation of these properties for details. - Create an implementation of
JsonConverterand annotate either the corresponding field or the containing class.JsonConverteris convenient if you want to use the same conversion logic on many fields. It also allows you to support a type within collections. Check out these examples.
Build configuration #
Aside from setting arguments on the associated annotation classes, you can also
configure code generation by setting values in build.yaml.
targets:
$default:
builders:
json_serializable:
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



