json_serializable 0.4.0

  • README.md
  • CHANGELOG.md
  • Installing
  • Versions
  • 94

Build Status

Provides source_gen Generators to create code for JSON serialization and deserialization.

See the example package to understand how to configure your project.

User defined and generated code

Given a library example.dart with an Person class annotated with @JsonSerializable():

library json_serializable.example;

import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';

@JsonSerializable()
class Person extends Object with _$PersonSerializerMixin {
  final String firstName;
  @JsonKey(includeIfNull: false)
  final String middleName;
  final String lastName;

  @JsonKey(name: 'date-of-birth', nullable: false)
  final DateTime dateOfBirth;

  @JsonKey(name: 'last-order')
  final DateTime lastOrder;

  @JsonKey(nullable: false)
  List<Order> orders;

  Person(this.firstName, this.lastName, this.dateOfBirth,
      {this.middleName, this.lastOrder, List<Order> orders})
      : this.orders = orders ?? <Order>[];

  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
}

Building creates the corresponding part example.g.dart:

Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
    json['firstName'] as String,
    json['lastName'] as String,
    DateTime.parse(json['date-of-birth'] as String),
    middleName: json['middleName'] as String,
    lastOrder: json['last-order'] == null
        ? null
        : DateTime.parse(json['last-order'] as String),
    orders: (json['orders'] as List)
        .map((e) => new Order.fromJson(e as Map<String, dynamic>))
        .toList());

abstract class _$PersonSerializerMixin {
  String get firstName;
  String get middleName;
  String get lastName;
  DateTime get dateOfBirth;
  DateTime get lastOrder;
  List<Order> get orders;
  Map<String, dynamic> toJson() {
    var $map = <String, dynamic>{};
    void $writeNotNull(String key, dynamic value) {
      if (value != null) {
        $map[key] = value;
      }
    }

    $map['firstName'] = firstName;
    $writeNotNull('middleName', middleName);
    $map['lastName'] = lastName;
    $map['date-of-birth'] = dateOfBirth.toIso8601String();
    $map['last-order'] = lastOrder?.toIso8601String();
    $map['orders'] = orders;
    return $map;
  }
}

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.

1. Depend on it

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


dependencies:
  json_serializable: "^0.4.0"

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
0.4.0 Feb 23, 2018 Go to the documentation of json_serializable 0.4.0 Download json_serializable 0.4.0 archive
0.3.2 Feb 12, 2018 Go to the documentation of json_serializable 0.3.2 Download json_serializable 0.3.2 archive
0.3.1+2 Feb 3, 2018 Go to the documentation of json_serializable 0.3.1+2 Download json_serializable 0.3.1+2 archive
0.3.1+1 Jan 18, 2018 Go to the documentation of json_serializable 0.3.1+1 Download json_serializable 0.3.1+1 archive
0.3.1 Jan 4, 2018 Go to the documentation of json_serializable 0.3.1 Download json_serializable 0.3.1 archive
0.3.0 Dec 15, 2017 Go to the documentation of json_serializable 0.3.0 Download json_serializable 0.3.0 archive
0.2.5 Nov 2, 2017 Go to the documentation of json_serializable 0.2.5 Download json_serializable 0.2.5 archive
0.2.4+1 Oct 2, 2017 Go to the documentation of json_serializable 0.2.4+1 Download json_serializable 0.2.4+1 archive
0.2.4 Sep 27, 2017 Go to the documentation of json_serializable 0.2.4 Download json_serializable 0.2.4 archive
0.2.3+1 Sep 19, 2017 Go to the documentation of json_serializable 0.2.3+1 Download json_serializable 0.2.3+1 archive

All 18 versions...

Analysis

This feature is new.
We welcome feedback.
More details: scoring.

We analyzed this package, and provided a score, details, and suggestions below.

  • completed on Feb 23, 2018
  • Dart: 2.0.0-dev.20.0
  • pana: 0.10.1

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
89 / 100
Health:
Code health derived from static analysis. [more]
100 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100 / 100
Overall score:
Weighted score of the above. [more]
94

Platforms

Detected platforms: other

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

Suggestions

  • The description is too short.

    Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

  • Maintain an example.

    Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use json_serializable.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev <2.0.0
analyzer >=0.29.10 <0.32.0 0.31.1 0.31.2-alpha.0
build >=0.9.0 <0.13.0 0.12.0+1
build_config ^0.2.1 0.2.3
cli_util ^0.1.0 0.1.2+1
json_annotation >=0.2.2 <0.2.3 0.2.2
path ^1.3.2 1.5.1
source_gen ^0.7.5 0.7.5+1
Transitive dependencies
args 1.4.0
async 2.0.3 2.0.4
charcode 1.1.1
convert 2.0.1
crypto 2.0.2+1
csslib 0.14.1
front_end 0.1.0-alpha.9 0.1.0-alpha.10
glob 1.1.5
html 0.13.2+2
isolate 1.1.0
kernel 0.3.0-alpha.9 0.3.0-alpha.10
logging 0.11.3+1
meta 1.1.2
package_config 1.0.3
plugin 0.2.0+2
source_span 1.4.0
string_scanner 1.0.2
typed_data 1.1.5
utf 0.9.0+4
watcher 0.9.7+7
yaml 2.1.13
Dev dependencies
build_runner ^0.7.0
build_test >=0.9.0 <0.11.0
collection ^1.14.0 1.14.5
dart_style ^1.0.0 1.0.9+1 1.0.10
test ^0.12.3