Viewing version 6.9.3. Open the latest package page.

json_serializable

6.9.3

Automatically generate code for converting to and from JSON by annotating Dart classes.

Download archive

Readme

Pub Package

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. 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 JsonLiteral annotation.

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.

Run dart run build_runner build in the 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:

  1. Setting properties on JsonKey annotating the target field.
  2. Set properties on JsonSerializable annotating the target type.
  3. 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:

  1. Specify the default rename logic for each enum value using fieldRename. For instance, use fieldRename: FieldRename.kebab to encode enum value noGood as "no-good".
  2. Force the generation of the enum helpers, even if the enum is 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(301)
  movedPermanently,
  @JsonValue(302)
  found,
  @JsonValue(500)
  internalServerError,
}

If you are annotating an enhanced enum, you can use JsonEnum.valueField to specify the field to use for the serialized value.

@JsonEnum(valueField: 'code')
enum StatusCodeEnhanced {
  success(200),
  movedPermanently(301),
  found(302),
  internalServerError(500);

  const StatusCodeEnhanced(this.code);
  final int code;
}

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, Record, Set, String, Uri

The collection types – Iterable, List, Map, Record, 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.

  1. If you own/control the desired type, add a fromJson constructor and/or a toJson() function to the type. Note: while you can use json_serializable for these types, you don't have to! The generator code only looks for these methods. It doesn't care how they were created.

    @JsonSerializable()
    class Sample1 {
      Sample1(this.value);
    
      factory Sample1.fromJson(Map<String, dynamic> json) =>
          _$Sample1FromJson(json);
    
      // Sample2 is NOT annotated with @JsonSerializable(), but that's okay
      // The class has a `fromJson` constructor and a `toJson` method, which is
      // all that is required.
      final Sample2 value;
    
      Map<String, dynamic> toJson() => _$Sample1ToJson(this);
    }
    
    class Sample2 {
      Sample2(this.value);
    
      // The convention is for `fromJson` to take a single parameter of type
      // `Map<String, dynamic>` but any JSON-compatible type is allowed.
      factory Sample2.fromJson(int value) => Sample2(value);
      final int value;
    
      // The convention is for `toJson` to take return a type of
      // `Map<String, dynamic>` but any JSON-compatible type is allowed.
      int toJson() => value;
    }
    
  2. Use the JsonKey.toJson and JsonKey.fromJson properties 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.

    @JsonSerializable()
    class Sample3 {
      Sample3(this.value);
    
      factory Sample3.fromJson(Map<String, dynamic> json) =>
          _$Sample3FromJson(json);
    
      @JsonKey(
        toJson: _toJson,
        fromJson: _fromJson,
      )
      final DateTime value;
    
      Map<String, dynamic> toJson() => _$Sample3ToJson(this);
    
      static int _toJson(DateTime value) => value.millisecondsSinceEpoch;
      static DateTime _fromJson(int value) =>
          DateTime.fromMillisecondsSinceEpoch(value);
    }
    
  3. Create an implementation of JsonConverter and annotate either the corresponding field or the containing class. JsonConverter is 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.

    @JsonSerializable()
    class Sample4 {
      Sample4(this.value);
    
      factory Sample4.fromJson(Map<String, dynamic> json) =>
          _$Sample4FromJson(json);
    
      @EpochDateTimeConverter()
      final DateTime value;
    
      Map<String, dynamic> toJson() => _$Sample4ToJson(this);
    }
    
    class EpochDateTimeConverter implements JsonConverter<DateTime, int> {
      const EpochDateTimeConverter();
    
      @override
      DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json);
    
      @override
      int toJson(DateTime object) => object.millisecondsSinceEpoch;
    }
    

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_field_map: false
          create_json_keys: false
          create_per_field_to_json: false
          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
Changelog

6.9.3

  • Error out if the target package does not have a language version of 3.0 or greater.

6.9.2

  • Support the latest package:analyzer.

6.9.1

  • Support the latest package:source_gen.
  • Require Dart 3.6

6.9.0

  • Use conditional map syntax to clean up null handling in toJson functions.
  • Fix core Dart type links in docs.
  • Require Dart 3.5

6.8.0

  • Add type arguments to Map literals used for Record serialization.
  • Add support for JsonSerializable(createJsonKeys: true). (#1401)
  • Handle decoding an int value from a double literal. This now matches the behavior of double values being encoded as int.

6.7.1

  • Support the latest package:analyzer.

6.7.0

  • Support Record types.
  • Require Dart 3.0
  • Require analyzer: ^5.12.0

6.6.2

  • Better handling of Object? or dynamic as fromJson constructor param.
  • Require Dart 2.19

6.6.1

  • Fix bug when JsonKey.includeToJson is false.

6.6.0

  • Support for JsonKey.includeFromJson and JsonKey.includeToJson.
  • Support JsonEnum.valueField being set with 'index'.
  • Support JsonSerializable.createPerFieldToJson.
  • Require Dart SDK >=2.18.0.
  • Require analyzer: ^5.2.0
  • Require json_annotation: '>=4.8.0 <4.9.0'

6.5.4

  • Fixed handling of nullable fields with converters which return non-nullable values.

6.5.3

  • Fixed handling of nullable enum fields with includeIfNull: false.

6.5.2

  • Better handling of null when encoding enum values or values with conversions.

6.5.1

  • Fixed BigInt, DateTime, and Uri support for JsonKey.defaultValue with a function value.

6.5.0

  • Allow constructors to be passed to JsonKey parameters that support Function types.
  • Accept Function values for JsonKey.defaultValue. The provided Function will be invoked for the default value if the target JSON element is missing or null.

6.4.1

  • Fixed a bug when an @JsonSerializable class uses a mixin with fields.
  • Added more documentation @JsonEnum.

6.4.0

  • Add support for JsonEnum.valueField which allows specifying a field in an "enhanced enum" to use for serialization instead of specifying each value individually with `JsonValue
  • Require json_annotation: '>=4.7.0 <4.8.0'

6.3.2

  • Require analyzer: '>=4.6.0 <6.0.0'
  • Require sdk: '>=2.17.0 <3.0.0'

6.3.1

  • Fixed support for Duration fields with default values. (#1170)

6.3.0

  • Added support for generating _$ExampleFieldMap, which can be used by other code-generators that needs to interact with JSON serialization. (#1164)
  • Added support for using a JsonConverter<MyClass, Object> on properties of type MyClass?. (#822)
  • Added support for JsonSerializable(converters: <JsonConverter>[]) (#1072)
  • Fix issue with serialization of non-nullable enumerations emitting a nullable type (#1146)

6.2.0

  • Added support for the new FieldRename.screamingSnake field in package:json_annotation.

6.1.6

  • Allow latest package:analyzer.

6.1.5

  • Fix enum support for upcoming enhanced enums in Dart 2.17.

6.1.4

  • Fix issues with latest package:analyzer related to enums and annotations.

6.1.3

  • Allow latest package:analyzer.

6.1.2

  • Fix issue with nested generics and genericArgumentFactories: true. (#1047)

6.1.1

  • Fix JsonKey.readValue support to allow static functions.

6.1.0

  • Support JsonKey.readValue to allow customized reading of values from source JSON map objects.
  • The check to make sure there is a correctly constrained dependency on package:json_annotation is now a warning and doesn't fail the build.
  • Require json_annotation '>=4.4.0 <4.5.0'.

6.0.1

  • Don't require json_annotation in dependencies if it's just used in tests.

6.0.0

  • Added support for JsonSerializable.constructor to allow specifying an alternative constructor to invoke when creating a fromJson helper.
  • Support the new @JsonEnum annotation in package:json_annotation.
  • Support JsonKey.nullForUndefinedEnumValue as a value for JsonKey.unknownEnumValue when you want to use null as the unknown value.
  • Use the new $enumDecodeNullable and $enumDecode in `json_annotation' instead of generating these for each library. NOTE: This is a potential breaking change if any user code relies on the previously generated private functions.
  • The builder now checks to make sure there is a correctly constrained dependency on package:json_annotation.
  • Require Dart SDK >=2.14.0.
  • Require json_annotation '>=4.3.0 <4.4.0'.

5.0.2

  • Include type arguments when invoking fromJson on custom types. This fixes an edge case where the generic arguments could not be inferred.

5.0.1

  • Correctly handle nullable custom objects within Iterable and Map.
  • Require the latest package:source_helper.

5.0.0

  • Use the default value for optional constructor parameters if JsonKey.defaultValue is not provided. This could be a breaking behavior change in generated code in some cases.
  • Fixed fromJson for Map fields with nullable values.
  • Improve names of private classes generated for toJson and fromJson.
  • Use the new $checkedCreate helper exposed in package:json_annotation v4.1+.
  • Generated code now conforms to this prefer_expression_function_bodies lint.
  • Support default values and types with a fromJson constructor.
  • Support default values with class- and function-based converters.
  • type_helper.dart:
    • BREAKING: removed typeArgumentsOf. This is now an extension exposed by package:source_helper.
  • Require package:analyzer ^2.0.0.

4.1.4

  • Allow the latest package:json_annotation.

4.1.3

  • Correctly handle nullable types with type arguments in generated code.

4.1.2

  • Correctly decode Map<String, double> when the input has int literals.

4.1.1

  • Allow the latest package:build_config.

4.1.0

  • Implementation is now null-safe.

  • Correctly handle nullable generic fields (T?) with genericArgumentFactories.

  • type_helper.dart - BREAKING changes

    • The API is now null-safe.
    • new KeyConfig class replaces JsonKey.
    • new ClassConfig class replaces JsonSerializable.

4.0.3

  • Correctly handle nullable values with genericArgumentFactories.
  • Require the latest package:build.

4.0.2

  • Correctly handle nullable Map and Iterable JSON types exposed by both class- and function-based converters.

4.0.1

  • Allow latest package:analyzer.

4.0.0

  • Requires Dart 2.12 or greater.
  • Generates null-safe code.
    • The nullable field on JsonKey ignored. The nullability of a field is now determined by the Dart type system.
  • BREAKING bool defaultProvided arg added to TypeHelper.deserialize. Only applies to code using TypeHelper directly.

3.5.2

  • Widen package:analyzer range to allow v1.x.

3.5.1

  • Improved error messages for unsupported types.
  • package:json_serializable/type_helper.dart
    • Made the third parameter to UnsupportedTypeError positional (optional).
  • Require package:analyzer >=0.39.0 <0.42.0.

3.5.0

  • Added support for populating generic helper functions for fields with generic type parameters.

  • Added support for JsonSerializable.genericArgumentFactories. This adds extra parameters to generated fromJson and/or toJson functions to support encoding and decoding generic types.

    For example, the generated code for

    @JsonSerializable(genericArgumentFactories: true)
    class Response<T> {
      int status;
      T value;
    }
    

    Looks like

    Response<T> _$ResponseFromJson<T>(
      Map<String, dynamic> json,
      T Function(Object json) fromJsonT,
    ) {
      return Response<T>()
        ..status = json['status'] as int
        ..value = fromJsonT(json['value']);
    }
    
    Map<String, dynamic> _$ResponseToJson<T>(
      Response<T> instance,
      Object Function(T value) toJsonT,
    ) =>
        <String, dynamic>{
          'status': instance.status,
          'value': toJsonT(instance.value),
        };
    
  • JsonKey.unknownEnumValue: Added support for Iterable, List, and Set.

  • Require package:analyzer >=0.39.0 <0.41.0.

3.4.1

  • Support properties where the getter is defined in a class with a corresponding setter in a super type.

3.4.0

  • JsonKey.defaultValue
    • Added support for double.infinity, double.negativeInfinity, and double.nan.
    • Added support for Set literals.
  • Require at least Dart 2.7.0.

3.3.0

  • Add support for fields annotated subclasses of JsonKey.
  • Export the following TypeHelper implementations and interfaces in package:json_serializable/type_helper.dart:
    • DurationHelper
    • TypeHelperContextWithConfig

3.2.5

  • Fix lint affecting pub.dev score.

3.2.4

  • Require package:analyzer ^0.39.0.

3.2.3

  • Fixed bug related to package:analyzer 0.38.5.

3.2.2

  • Support JsonConverter annotations on property getters

3.2.1

  • Support package:analyzer >=0.33.3 <0.39.0

3.2.0

  • Require package:json_annotation ^3.0.0.
  • Added support for JsonSerializable.ignoreUnannotated.
  • Added support for JsonKey.unknownEnumValue.
  • Small change to how enum support code is generated.
  • Require at least Dart 2.3.0.

3.1.0

  • Support Map keys of type int, BigInt, DateTime, and Uri.
  • Trailing commas are now added to generated constructor arguments and the elements in Map literals.
  • Support package:analyzer >=0.33.3 <0.38.0

3.0.0

This release is entirely BREAKING changes. It removes underused features that added disproportionate complexity to this package. This cleanup should ease future feature work.

  • Removed support for JsonSerializable.useWrappers.
  • Removed support for JsonSerializable.generateToJsonFunction.
  • Removed support for encodeEmptyCollection.
  • If a field has a conversion function defined – either JsonKey.toJson or a custom JsonConverter annotation – don't intercept null values, even if nullable is explicitly set to false. This allows these functions to provide alternative values for null – such as an empty collection – which replaces the functionality provided by encodeEmptyCollection.
    • NOTE: this is SILENTLY BREAKING. There is no corresponding deprecation for this change. If you use converters, please make sure to test your code!

2.3.0

  • Added pascal as an additional fieldRename option.

2.2.3

  • Removed special handling of undefined types due to changes in package:analyzer. These types are now treated as dynamic.

2.2.2

  • Require at least Dart 2.2.0.
  • Allow build_config 0.4.x.

2.2.1

  • Fixed an error when a property/field is defined in a mixin.

2.2.0

  • If a field has a conversion function defined – either JsonKey.toJson or a custom JsonConverter annotation – handle the case where the function returns null and both nullable and includeIfNull are false.

2.1.2

  • Support package:json_annotation >=2.1.0 <2.3.0.

2.1.1

  • Support package:analyzer >=0.33.3 <0.37.0

2.1.0

  • Require at least Dart 2.1.1.

  • Added support for encodeEmptyCollection on JsonKey and JsonSerializable.

  • Added support for BigInt.

  • Added BigIntTypeHelper to type_helper.dart library.

  • Provide a more helpful error if the builder is improperly configured.

2.0.3

  • When invoking a fromJson constructor on a field type, generate a conversion expression derived from the constructor parameter type.

  • Be more strict about the supported List, Set, or Map types. This may cause errors to be raised in cases where invalid code was generated before. It also allows implementations of these types to add a fromJson constructor to support custom decoding.

  • Small change to the whitespace around converted maps to improve a very slow path when formatting generated code.

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 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 {
      none,
      dependents,
      @JsonValue('all_packages')
      allPackages,
      @JsonValue('root_package')
      rootPackage
    }
    
  • 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 the JSON map, but its 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 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 support 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.

Installing

export PUB_HOSTED_URL=https://pub.mirror.p-hatan.ir
flutter pub add 'json_serializable:6.9.3'
pubspec.yaml
name: json_serializable
version: 6.9.3
description: >-
  Automatically generate code for converting to and from JSON by annotating
  Dart classes.
repository: https://github.com/google/json_serializable.dart/tree/master/json_serializable
environment:
  sdk: ^3.6.0
topics:
 - json
 - build-runner
 - json-serializable
 - codegen

resolution: workspace

dependencies:
  analyzer: '>=6.5.0 <8.0.0'
  async: ^2.10.0
  build: ^2.4.1
  build_config: ^1.1.0
  collection: ^1.17.0
  dart_style: '>=2.3.7 <4.0.0'

  # Use a tight version constraint to ensure that a constraint on
  # `json_annotation` properly constrains all features it provides.
  json_annotation: '>=4.9.0 <4.10.0'
  meta: ^1.14.0
  path: ^1.9.0
  pub_semver: ^2.1.4
  pubspec_parse: ^1.0.0
  source_gen: ^2.0.0
  source_helper: ^1.3.4

dev_dependencies:
  _json_serial_shared_test:
    path: ../shared_test
  build_runner: ^2.4.6
  build_verify: ^3.0.0
  logging: ^1.0.0
  source_gen_test: ^1.0.6
  test: ^1.24.4
  test_descriptor: ^2.0.0
  test_process: ^2.0.0
  yaml: ^3.0.0

Version history

VersionPublishedArchiveSHA-256
0.1.0Cached · Upstream SHA-256 matchedDownloadea38aff2…357ce4
0.1.0+1Cached · Upstream SHA-256 matchedDownload54608c1f…fae3e4
0.2.0Cached · Upstream SHA-256 matchedDownload228de10d…0dc07d
0.2.0+1Cached · Upstream SHA-256 matchedDownloadbc4de154…cd2c76
0.2.1Cached · Upstream SHA-256 matchedDownload925b3d51…19cab5
0.2.2Cached · Upstream SHA-256 matchedDownload4bde8d44…7c6625
0.2.2+1Cached · Upstream SHA-256 matchedDownload06b55410…03b5cf
0.2.3Cached · Upstream SHA-256 matchedDownload98f510ad…eac912
0.2.3+1Cached · Upstream SHA-256 matchedDownloade6363ffc…0f3f04
0.2.4Cached · Upstream SHA-256 matchedDownload332c5d27…4db89f
0.2.4+1Cached · Upstream SHA-256 matchedDownload9ee6223b…9cd202
0.2.5Cached · Upstream SHA-256 matchedDownload25d0c6df…5da947
0.3.0Cached · Upstream SHA-256 matchedDownload8970e927…c017f6
0.3.1Cached · Upstream SHA-256 matchedDownload4d856bb2…1086ee
0.3.1+1Cached · Upstream SHA-256 matchedDownloadceaa1075…d43605
0.3.1+2Cached · Upstream SHA-256 matchedDownload7576a95d…9b2e9d
0.3.2Cached · Upstream SHA-256 matchedDownload8fc35438…08ba16
0.4.0Cached · Upstream SHA-256 matchedDownload52fca6a7…bbb0d5
0.5.0Cached · Upstream SHA-256 matchedDownloadceb97da7…f705f8
0.5.1Cached · Upstream SHA-256 matchedDownload555278a0…31b474
0.5.2Cached · Upstream SHA-256 matchedDownload4a477c42…dea9df
0.5.3Cached · Upstream SHA-256 matchedDownload453fab42…39f3f8
0.5.4Cached · Upstream SHA-256 matchedDownload2b743d72…be94c7
0.5.4+1Cached · Upstream SHA-256 matchedDownload8e4f2cfa…4fc7de
0.5.5Cached · Upstream SHA-256 matchedDownload825ff2da…d2676c
0.5.6Cached · Upstream SHA-256 matchedDownload11092952…b28665
0.5.7Cached · Upstream SHA-256 matchedDownloadafd52873…21feff
0.5.8Cached · Upstream SHA-256 matchedDownload56d661f5…19ac8b
0.5.8+1Cached · Upstream SHA-256 matchedDownload6c80bfb5…d03209
1.0.0Cached · Upstream SHA-256 matchedDownloadca0c6ffc…e59fc5
1.0.1Cached · Upstream SHA-256 matchedDownloadc1479f04…3d14ee
1.1.0Cached · Upstream SHA-256 matchedDownload46d41e4f…df92f9
1.2.0Cached · Upstream SHA-256 matchedDownload4075e577…1b11b7
1.2.1Cached · Upstream SHA-256 matchedDownload8629d4cb…9de3dc
1.3.0Cached · Upstream SHA-256 matchedDownload0236f7f0…a15438
1.4.0Cached · Upstream SHA-256 matchedDownload394035ff…d1641c
1.5.0Cached · Upstream SHA-256 matchedDownload086663d3…fae00b
1.5.1Cached · Upstream SHA-256 matchedDownload977f3916…91f75b
2.0.0Cached · Upstream SHA-256 matchedDownload0b0a7239…f467f4
2.0.1Cached · Upstream SHA-256 matchedDownloade314d1da…a97c4f
2.0.2Cached · Upstream SHA-256 matchedDownload31fc6262…16290c
2.0.3Cached · Upstream SHA-256 matchedDownload12a5cfd6…199157
2.1.0Cached · Upstream SHA-256 matchedDownload330b4534…674a33
2.1.1Cached · Upstream SHA-256 matchedDownload9fb477f1…8ff6b9
2.1.2Cached · Upstream SHA-256 matchedDownload744218d0…9167e3
2.2.0Cached · Upstream SHA-256 matchedDownload35995d69…dcfe7b
2.2.1Cached · Upstream SHA-256 matchedDownload2dbfe302…23d088
2.2.2Cached · Upstream SHA-256 matchedDownload33166f5f…53ca39
2.3.0Cached · Upstream SHA-256 matchedDownloadc132f057…8d9ab2
3.0.0Cached · Upstream SHA-256 matchedDownload48d5294c…082144
3.1.0Cached · Upstream SHA-256 matchedDownload200067f1…872db6
3.2.0Cached · Upstream SHA-256 matchedDownload3c157eae…aba16d
3.2.1Cached · Upstream SHA-256 matchedDownload4c198769…eb5690
3.2.2Cached · Upstream SHA-256 matchedDownload358bed36…505f0c
3.2.3Cached · Upstream SHA-256 matchedDownload4ea7527e…908178
3.2.4Cached · Upstream SHA-256 matchedDownload8717e5f5…f655fd
3.2.5Cached · Upstream SHA-256 matchedDownload62aa4c18…96ec5c
3.3.0Cached · Upstream SHA-256 matchedDownloadf30cdc18…5eee4d
3.4.0Cached · Upstream SHA-256 matchedDownloadb198894a…a89ac9
3.4.1Cached · Upstream SHA-256 matchedDownload47222df0…cecf87
3.5.0Cached · Upstream SHA-256 matchedDownload8000c8f8…cc15f7
3.5.1Cached · Upstream SHA-256 matchedDownload698f328e…e4bab5
3.5.2Cached · Upstream SHA-256 matchedDownload0f9e7274…71bf71
4.0.0-nullsafety.0Cached · Upstream SHA-256 matchedDownload65086760…4d8130
4.0.0Cached · Upstream SHA-256 matchedDownloadbf5cd59a…50e4e3
4.0.1Cached · Upstream SHA-256 matchedDownloadf9f62b88…b2677e
4.0.2Cached · Upstream SHA-256 matchedDownloadc29fcdae…9ab2bc
4.0.3Cached · Upstream SHA-256 matchedDownloadc17fe901…049696
4.1.0Cached · Upstream SHA-256 matchedDownload04a71e61…0ec003
4.1.1Cached · Upstream SHA-256 matchedDownload194d4ffc…746aa0
4.1.2Cached · Upstream SHA-256 matchedDownloade58e35c2…2b5dba
4.1.3Cached · Upstream SHA-256 matchedDownloadbd4c3eec…990338
4.1.4Cached · Upstream SHA-256 matchedDownload86d3edf6…3bb323
5.0.0Cached · Upstream SHA-256 matchedDownloade55b5148…5ed5cd
5.0.1Cached · Upstream SHA-256 matchedDownloade760d5cf…bf636c
5.0.2Cached · Upstream SHA-256 matchedDownload4af86580…04cc1c
6.0.0Cached · Upstream SHA-256 matchedDownload5a0f38bb…21beb8
6.0.1Cached · Upstream SHA-256 matchedDownload45234e44…a4b23c
6.1.0Cached · Upstream SHA-256 matchedDownload64965139…038587
6.1.1Cached · Upstream SHA-256 matchedDownload9baed298…ead1cb
6.1.2Cached · Upstream SHA-256 matchedDownloadc7119ff7…7c1a31
6.1.3Cached · Upstream SHA-256 matchedDownload85f3e219…d57cfc
6.1.4Cached · Upstream SHA-256 matchedDownloaddc6f9551…1ee8ca
6.1.5Cached · Upstream SHA-256 matchedDownloada53cf24d…a08610
6.1.6Cached · Upstream SHA-256 matchedDownload3feab8c3…b10f39
6.2.0Cached · Upstream SHA-256 matchedDownload4fc3fb22…aee75d
6.3.0Cached · Upstream SHA-256 matchedDownload40e713f3…a90f13
6.3.1Cached · Upstream SHA-256 matchedDownload0cec7060…ee8238
6.3.2Cached · Upstream SHA-256 matchedDownloadfd1bcfbf…116932
6.4.0Cached · Upstream SHA-256 matchedDownload276b80dd…a54202
6.4.1Cached · Upstream SHA-256 matchedDownload581006a3…7cfe4b
6.5.0Cached · Upstream SHA-256 matchedDownload45205106…757fe9
6.5.1Cached · Upstream SHA-256 matchedDownload2296021b…f04bb4
6.5.2Cached · Upstream SHA-256 matchedDownloadf8aec50d…c97f74
6.5.3Cached · Upstream SHA-256 matchedDownload87ce738d…c2bfb0
6.5.4Cached · Upstream SHA-256 matchedDownloadf3c2c18a…53ef5d
6.6.0Cached · Upstream SHA-256 matchedDownload040088d9…700a75
6.6.1Cached · Upstream SHA-256 matchedDownloaddadc08bd…8d187a
6.6.2Cached · Upstream SHA-256 matchedDownload43793352…c04dc7
6.7.0Cached · Upstream SHA-256 matchedDownload61a60716…2325c4
6.7.1Cached · Upstream SHA-256 matchedDownloadaa1f5a89…b0b969
6.8.0Cached · Upstream SHA-256 matchedDownloadea1432d1…a1fd4b
6.9.0Cached · Upstream SHA-256 matchedDownloadc2fcb392…050d7c
6.9.1Cached · Upstream SHA-256 matchedDownloade7855a40…7154b4
6.9.2Cached · Upstream SHA-256 matchedDownload8f52361c…05d571
6.9.3Cached · Upstream SHA-256 matchedDownloadb0a98230…dd59c9
6.9.4Cached · Upstream SHA-256 matchedDownload81f04dee…c9e58a
6.9.5Cached · Upstream SHA-256 matchedDownloadc50ef5fc…feea8c
6.10.0-devCached · Upstream SHA-256 matchedDownloadab72b330…666393
6.10.0Cached · Upstream SHA-256 matchedDownloadce2cf974…55be27
6.11.0Cached · Upstream SHA-256 matchedDownload3f2913b7…b80cbd
6.11.1Cached · Upstream SHA-256 matchedDownload33a04066…3aa6fe
6.11.2Cached · Upstream SHA-256 matchedDownloadc5b2ee75…fdffa3
6.11.3Cached · Upstream SHA-256 matchedDownload6b253f78…e0b5b1
6.11.4Cached · Upstream SHA-256 matchedDownload5b89c1e3…f8104e
6.12.0Cached · Upstream SHA-256 matchedDownload93fba3ad…25760d
6.13.0Cached · Upstream SHA-256 matchedDownload44729f5c…16a6c0
6.13.1Cached · Upstream SHA-256 matchedDownloadfbcf404b…a78925
6.13.2Cached · Upstream SHA-256 matchedDownload2c15e78e…7f20db
6.14.0Cached · Upstream SHA-256 matchedDownloadffcd10cd…97e501
6.14.1Cached · Upstream SHA-256 matchedDownloade45aefa0…63113d
6.15.0Cached · Upstream SHA-256 matchedDownloadeb8d06bc…b541f8
6.15.1Cached · Upstream SHA-256 matchedDownload3b177bc1…fd0f33
6.15.2Cached · Upstream SHA-256 matchedDownloadcc782276…1c66f1

Dependencies

analyzer "\u003e=6.5.0 \u003c8.0.0"

async "^2.10.0"

build "^2.4.1"

build_config "^1.1.0"

collection "^1.17.0"

dart_style "\u003e=2.3.7 \u003c4.0.0"

json_annotation "\u003e=4.9.0 \u003c4.10.0"

meta "^1.14.0"

path "^1.9.0"

pub_semver "^2.1.4"

pubspec_parse "^1.0.0"

source_gen "^2.0.0"

source_helper "^1.3.4"