json_serializable 2.0.2

  • README.md
  • Example
  • Installing
  • Versions
  • 97

Build Status

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 to JsonSerializable to configure the generated code. You can also customize individual fields by annotating them with JsonKey and providing custom arguments.

  • To generate a Dart field with the contents of a file containting JSON, use the JsonLiteral annotation.

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(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);

Building creates the corresponding part example.g.dart:

part of 'example.dart';

Person _$PersonFromJson(Map<String, dynamic> json) {
  return Person(
      firstName: json['firstName'] as String,
      lastName: json['lastName'] as String,
      dateOfBirth: DateTime.parse(json['dateOfBirth'] as String));

Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
      'firstName': instance.firstName,
      'lastName': instance.lastName,
      'dateOfBirth': instance.dateOfBirth.toIso8601String()

Build configuration #

Besides setting arguments on the associated annotation classes, you can also configure code generation by setting values in build.yaml.

          # Options configure how source code is generated for every
          # `@JsonSerializable`-annotated class in the package.
          # The default value for each is listed.
          # For usage information, reference the corresponding field in
          # `JsonSerializableGenerator`.
          any_map: false
          checked: false
          create_factory: true
          create_to_json: true
          disallow_unrecognized_keys: false
          explicit_to_json: false
          field_rename: none
          generate_to_json_function: true
          include_if_null: true
          nullable: true
          use_wrappers: false

2.0.2 #

  • Log warnings when JsonKey.defaultValue is set with other fields.

    • With toJson: use nullable: false instead of defaultValue.
    • With both disallowNullValue and required set to true.
  • Avoid no-op call to map when decoding a field of type Set.

  • Support package:analyzer >=0.33.3 <0.36.0

2.0.1 #

  • Support package:analyzer v0.34.0.

2.0.0 #

  • Support all build.yaml configuration options on classes by adding a number of fields to JsonSerializable: anyMap, checked, explicitToJson, generateToJsonFunction, and useWrappers.

  • Support decode/encode of dart:core Duration

  • Code generated for fields and classes annotated with JsonConverter instances now properly handles nullable fields.

  • Build configuration

    • You can now configure all settings exposed by the JsonSerializable annotation within build.yaml.

    • BREAKING Unsupported options defined in build.yaml will cause exceptions instead of being logged and ignored.

  • json_serializable.dart

    • BREAKING JsonSerializableGenerator now exposes a config property of type JsonSerializable instead of individual properties for checked, anyMay, etc. This will affect anyone creating or using this class via code.
  • type_helper.dart

    • BREAKING SerializeContext and DeserializeContext have been replaced with new TypeHelperContext class.

    • TypeHelper now has a type argument allowing implementors to specify a specific implementation of TypeHelperContext for calls to serialize and deserialize. Many of the included TypeHelper implementations have been updated to indicate they expect more information from the source generator.

1.5.1 #

  • Support the latest package:analyzer.

1.5.0 #

  • Added support for JsonConvert annotation on fields.

1.4.0 #

  • type_helper.dart

    • TypeHelper serialize and deserialize have return type Object instead of String. This allows coordination between instances to support more advanced features – like using the new LambdaResult class to avoid creating unnecessary lambdas. When creating TypeHelper implementations, handle non-String results by calling toString() on unrecognized values.
  • Declare support for package:build version 1.x.x.

1.3.0 #

  • Add support for types annotated with classes that extend JsonConverter from package:json_annotation.

  • Export the following TypeHelper implementations in package:json_serializable/type_helper.dart: ConvertHelper, EnumHelper, IterableHelper, JsonConverterHelper, MapHelper, ValueHelper

  • Added support for Set type as a target.

1.2.1 #

  • Added back const for maps generated with checked: true configuration.

1.2.0 #

  • Now throws InvalidGenerationSourceError instead of UnsupportedError for some classes of constructor errors.

  • Supports class-static functions for toJson and fromJson on JsonKey.

  • Provide a warning about ignored setter-only properties instead of crashing.

  • Added back const for lists generated with disallowUnrecognizedKeys, required, and disallowNullValue.

  • Fixed a bug when disallowUnrecognizedKeys is enabled.

  • Fixed a number of issues when dealing with inherited properties.

1.1.0 #

  • Added support for automatically converting field names to JSON map keys as kebab-case or snake_case with a new option on the JsonSerializable annotation.

1.0.1 #

  • Explicit new and const are no longer generated.

1.0.0 #

  • BREAKING By default, code generated to support toJson now creates a top-level function instead of a mixin. The default for the generate_to_json_function is now true. To opt-out of this change, set generate_to_json_function to false.

  • Now supports changing the serialized values of enums using JsonValue.

    enum AutoApply {
  • JsonSerializableGenerator.generateForAnnotatedElement now returns Iterable<String> instead of String.

  • SerializeContext and DeserializeContext now have an addMember function which allows TypeHelper instances to add additional members when handling a field. This is useful for generating shared helpers, for instance.

  • BREAKING The header option is no longer supported and must be removed from build.yaml.

  • If a manual build script is used the json_serializable builder must be switched to hideOutput: true, and the combiningBuilder from source_gen must be included following this builder. When using a generated build script with pub run build_runner or webdev this is handled automatically.

0.5.8+1 #

  • Support the Dart 2.0 stable release.

0.5.8 #

  • Small fixes to support Dart 2 runtime semantics.

  • Support serializing types provided by platform-specific libraries (such as Flutter) if they use custom convert functions.

0.5.7 #

  • Added support for JsonKey.required.

    • When true, generated code throws a MissingRequiredKeysException if the key does not exist in the JSON map used to populate the annotated field.
    • Will be captured and wrapped in a CheckedFromJsonException if checked is enabled in json_serializable.
  • Added JsonKey.disallowNullValue.

    • When true, generated code throws a DisallowedNullValueException if the corresponding keys exist in in the JSON map, but it's value is null.
    • Will be captured and wrapped in a CheckedFromJsonException if checked is enabled in json_serializable.
  • Added support for Uri conversion.

  • Added missing checked parameter to the JsonSerializableGenerator.withDefaultHelpers constructor.

  • Added explicit_to_json configuration option.

    • See JsonSerializableGenerator.explicitToJson for details.
  • Added generate_to_json_function configuration option.

    • See JsonSerializableGenerator.generateToJsonFunction for details.

0.5.6 #

  • Added support for JsonSerializable.disallowUnrecognizedKeys.
    • Throws an UnrecognizedKeysException if it finds unrecognized keys in the JSON map used to populate the annotated field.
    • Will be captured and wrapped in a CheckedFromJsonException if checked is enabled in json_serializable.
  • All fromJson constructors now use block syntax instead of fat arrows.

0.5.5 #

  • Added support for JsonKey.defaultValue.

  • enum deserialization now uses helpers provided by json_annotation.

  • Small change to how nullable Map values are deserialized.

  • Small whitespace changes to JsonLiteral generation to align with dartfmt.

  • Improve detection of toJson and fromJson in nested types.

0.5.4+1 #

  • Fixed a bug introduced in 0.5.4 in some cases where enum values are nested in collections.

0.5.4 #

  • Add checked configuration option. If true, generated fromJson functions include extra checks to validate proper deserialization of types.

  • Added any_map to configuration. Allows fromJson code to support dynamic Map instances that are not explicitly Map<String, dynaimc>.

  • Added support for classes with type arguments.

  • Use Map.map for more map conversions. Simplifies generated code and fixes a subtle issue when the Map key type is dynamic or Object.

0.5.3 #

  • Require the latest version of package:analyzer - v0.32.0.

  • If JsonKey.fromJson function parameter is Iterable or Map with type arguments of dynamic or Object, omit the arguments when generating a cast. _myHelper(json['key'] as Map) instead of _myHelper(json['key'] as Map<dynamic, dynamic>).

  • JsonKey.fromJson/.toJson now support functions with optional arguments.

0.5.2 #

  • If JsonKey.fromJson/toJson are set, apply them before any custom or default TypeHelper instances. This allows custom DateTime parsing, by preempting the existing DateTime TypeHelper.

0.5.1 #

  • Support new fromJson and toJson fields on JsonKey.

  • Use log exposed by package:build. This requires end-users to have at least package:build_runner ^0.8.2.

  • Updated minimum package:source_gen dependency to 0.8.1 which includes improved error messages.

0.5.0 #

  • BREAKING Removed deprecated support for require_library_directive / requireLibraryDirective in build_runner configuration.

  • BREAKING Removed the deprecated generators.dart library.

  • BREAKING Removed jsonPartBuilder function from public API.

  • Support the latest package:source_gen.

  • Private and ignored fields are now excluded when generating serialization and deserialization code by using @JsonKey(ignore: true).

  • Throw an exception if a private field or an ignored field is referenced by a required constructor argument.

  • More comprehensive escaping of string literals.

package:json_serializable/type_helper.dart #

  • Breaking The nullable parameter on TypeHelper.serialize and .deserialize has been removed. It is now exposed in SerializeContext and DeserializeContext abstract classes as a read-only property.

  • Potentially Breaking The metadata property on SerializeContext and DeserializeContext is now readonly. This would potentially break code that extends these classes – which is not expected.

0.4.0 #

  • Potentially Breaking Inherited fields are now processed and used when generating serialization and deserialization code. There is a possibility that the generated code may change in undesired ways for classes annotated for v0.3.

  • Avoid unnecessary braces in string escapes.

  • Use single quotes when generating code.

0.3.2 #

  • The require_library_directive option now defaults to false. The option will be removed entirely in 0.4.0.

0.3.1+2 #

  • Support the latest version of the analyzer package.

0.3.1+1 #

  • Expanded package:build support to allow version 0.12.0.

0.3.1 #

  • Add a build.yaml so the builder can be consumed by users of build_runner version 0.7.0.

  • Now requires a Dart 2.0.0-dev release.

0.3.0 #

  • NEW top-level library json_serializable.dart.

    • Replaces now deprecated generators.dart to access JsonSerializableGenerator and JsonLiteralGenerator.

    • Adds the jsonPartBuilder function to make it easy to create a PartBuilder, without creating an explicit dependency on source_gen.

  • BREAKING UnsupportedTypeError added a new required constructor argument: reason.

  • BREAKING The deprecated annotations.dart library has been removed. Use package:json_annotation instead.

  • BREAKING The arguments to TypeHelper serialize and deserialize have changed.

    • SerializeContext and DeserializeContext (new classes) are now passed instead of the TypeHelperGenerator typedef (which has been deleted).
  • JsonSerializableGenerator now supports an optional useWrappers argument when generates and uses wrapper classes to (hopefully) improve the speed and memory usage of serialization – at the cost of more code.

    NOTE: useWrappers is not guaranteed to improve the performance of serialization. Benchmarking is recommended.

  • Make null field handling smarter. If a field is classified as not nullable, then use this knowledge when generating serialization code – even if includeIfNull is false.

0.2.5 #

  • Throw an exception if a duplicate JSON key is detected.

  • Support the nullable field on the JsonSerializable class annotation.

0.2.4+1 #

  • Throw a more helpful error when a constructor is missing.

0.2.4 #

  • Moved the annotations in annotations.dart to package:json_annotations.

    • Allows package authors to release code that has the corresponding annotations without requiring package users to inherit all of the transitive dependencies.
  • Deprecated annotations.dart.

0.2.3 #

  • Write out toJson methods more efficiently when the first fields written are not intercepted by the null-checking method.

0.2.2+1 #

  • Simplify the serialization of Map instances when no conversion is required for values.

  • Handle int literals in JSON being assigned to double fields.

0.2.2 #

  • Enable support for enum values.
  • Added asConst to JsonLiteral.
  • Improved the handling of Dart-specific characters in JSON strings.

0.2.1 #

  • Upgrade to package:source_gen v0.7.0

0.2.0+1 #

  • When serializing classes that implement their own fromJson constructor, honor their constructor parameter type.

0.2.0 #

  • BREAKING Types are now segmented into their own libraries.

    • package:json_serializable/generators.dart contains Generator implementations.

    • package:json_serializable/annotations.dart contains annotations. This library should be imported with your target classes.

    • package:json_serializable/type_helpers.dart contains TypeHelper classes and related helpers which allow custom generation for specific types.

  • BREAKING Generation fails for types that are not a JSON primitive or that do not explicitly supports JSON serialization.

  • BREAKING TypeHelper:

    • Removed can methods. Return null from (de)serialize if the provided type is not supported.

    • Added (de)serializeNested arguments to (de)serialize methods allowing generic types. This is how support for Iterable, List, and Map is implemented.

  • BREAKING JsonKey.jsonName was renamed to name and is now a named parameter.

  • Added support for optional, non-nullable fields.

  • Added support for excluding null values when generating JSON.

  • Eliminated all implicit casts in generated code. These would end up being runtime checks in most cases.

  • Provide a helpful error when generation fails due to undefined types.

0.1.0+1 #

  • Fix homepage in pubspec.yaml.

0.1.0 #

  • Split off from source_gen.

  • Add /* unsafe */ comments to generated output likely to be unsafe.

  • Support (de)serializing values in Map.

  • Fix ordering of fields when they are initialized via constructor.

  • Don't use static members when calculating fields to (de)serialize.


// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  json_serializable: ^2.0.2

2. Install it

You can install packages from the command line:

with pub:

$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:json_serializable/json_serializable.dart';
Version Uploaded Documentation Archive
2.0.2 Feb 4, 2019 Go to the documentation of json_serializable 2.0.2 Download json_serializable 2.0.2 archive
2.0.1 Dec 10, 2018 Go to the documentation of json_serializable 2.0.1 Download json_serializable 2.0.1 archive
2.0.0 Oct 23, 2018 Go to the documentation of json_serializable 2.0.0 Download json_serializable 2.0.0 archive
1.5.1 Oct 8, 2018 Go to the documentation of json_serializable 1.5.1 Download json_serializable 1.5.1 archive
1.5.0 Oct 3, 2018 Go to the documentation of json_serializable 1.5.0 Download json_serializable 1.5.0 archive
1.4.0 Sep 25, 2018 Go to the documentation of json_serializable 1.4.0 Download json_serializable 1.4.0 archive
1.3.0 Sep 18, 2018 Go to the documentation of json_serializable 1.3.0 Download json_serializable 1.3.0 archive
1.2.1 Aug 28, 2018 Go to the documentation of json_serializable 1.2.1 Download json_serializable 1.2.1 archive
1.2.0 Aug 28, 2018 Go to the documentation of json_serializable 1.2.0 Download json_serializable 1.2.0 archive
1.1.0 Aug 9, 2018 Go to the documentation of json_serializable 1.1.0 Download json_serializable 1.1.0 archive

All 41 versions...

Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Feb 14, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.13


Detected platforms: other

Primary library: package:json_serializable/json_serializable.dart with components: io, build, mirrors.

Health suggestions

Fix lib/src/field_helpers.dart. (-1 points)

Analysis of lib/src/field_helpers.dart reported 2 hints:

line 8 col 10: 'InheritanceManager' is deprecated and shouldn't be used.

line 81 col 19: 'InheritanceManager' is deprecated and shouldn't be used.

Maintenance suggestions

The package description is too short. (-5 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
analyzer >=0.33.3 <0.36.0 0.35.1
build >=0.12.6 <2.0.0 1.1.1
build_config >=0.2.6 <0.4.0 0.3.1+4
json_annotation >=2.0.0 <2.1.0 2.0.0
meta ^1.1.0 1.1.7
path ^1.3.2 1.6.2
source_gen ^0.9.0 0.9.4+1
Transitive dependencies
args 1.5.1
async 2.0.8
charcode 1.1.2
convert 2.1.1
crypto 2.0.6
csslib 0.14.6
front_end 0.1.11
glob 1.1.7
html 0.13.3+3
kernel 0.3.11
package_config 1.0.5
plugin 0.2.0+3
pub_semver 1.4.2
pubspec_parse 0.1.4
source_span 1.5.4
string_scanner 1.0.4
term_glyph 1.1.0
typed_data 1.1.6
utf 0.9.0+5
watcher 0.9.7+10
Dev dependencies
build_runner ^1.0.0
build_test ^0.10.0
build_verify ^1.1.0
build_web_compilers ^1.0.0
collection ^1.14.0 1.14.11
dart_style ^1.0.0 1.2.3
logging ^0.11.3+1 0.11.3+2
test ^1.3.3
yaml ^2.1.13 2.1.15