dart_json_mapper 1.1.12

  • Readme
  • Changelog
  • Example
  • Installing
  • 88

Build Status pub package

This package allows programmers to annotate Dart classes in order to Serialize / Deserialize them to / from JSON.

Why? #

  • Compatible with all Dart platforms, including Flutter and Web platforms
  • No need to extend your classes from any mixins/base/abstract classes to keep code leaner
  • Clean and simple setup, transparent and straightforward usage with no heavy maintenance
  • No extra boilerplate involved, 100% generated only
  • Custom converters per each class field, full control over the process
  • NO dependency on dart:mirrors, one of the reasons is described here.

Dart classes reflection mechanism is based on reflectable library. This means "extended types information" is auto-generated out of existing Dart program guided by the annotated classes only, as the result types information is accesible at runtime, at a reduced cost.

Typical Flutter.io project integration sample can be found here

Basic setup #

Please add the following dependencies to your pubspec.yaml:

  dart_json_mapper: any
  build_runner: any

Say, you have a dart program main.dart having some classes intended to be traveling to JSON and back.

  • First thing you should do is to put @jsonSerializable annotation on each of those classes
  • Next step is to auto generate main.reflectable.dart file. And afterwards import that file into main.dart


import 'package:dart_json_mapper/annotations.dart';
import 'package:dart_json_mapper/json_mapper.dart';

import 'main.reflectable.dart'; // Import generated code.

@jsonSerializable // This annotation let instances of MyData traveling to/from JSON
class MyData {
  int a = 123;

  @JsonProperty(ignore: true)
  bool b;

  @JsonProperty(name: 'd')
  String c;

  MyData(this.a, this.b, this.c);

main() {
  initializeReflectable(); // Imported from main.reflectable.dart
  print(JsonMapper.serialize(MyData(456, true, "yes")));
  "a": 456,
  "d": "yes"

Go ahead and create a build.yaml file in your project root directory. Then add the following content:

          - lib/main.dart
          formatted: true

Now run the code generation step with the root of your package as the current directory:

> pub run build_runner build

You'll need to re-run code generation each time you are making changes to lib/main.dart So for development time, use watch like this

> pub run build_runner watch

Each time you modify your project code, all *.reflectable.dart files will be updated as well.

  • Next step is to add "*.reflectable.dart" to your .gitignore
  • And this is it, you are all set and ready to go. Happy coding!

Format date / number types #

In order to format DateTime or num instance as a JSON string, it is possible to provide intl based formatting patterns.


@JsonProperty(converterParams: {'format': 'MM-dd-yyyy H:m:s'})
DateTime lastPromotionDate = DateTime(2008, 05, 13, 22, 33, 44);

@JsonProperty(converterParams: {'format': 'MM/dd/yyyy'})
DateTime hireDate = DateTime(2003, 02, 28);
"lastPromotionDate": "05-13-2008 22:33:44",
"hireDate": "02/28/2003"


@JsonProperty(converterParams: {'format': '##.##'})
num salary = 1200000.246;
"salary": "1200000.25"

As well, it is possible to utilize converterParams map to provide custom parameters to your custom converters.

Example with immutable class #

enum Color { Red, Blue, Green, Brown, Yellow, Black, White }

class Car {
    @JsonProperty(name: 'modelName')
    String model;
    @JsonProperty(enumValues: Color.values)
    Color color;
    @JsonProperty(ignore: true)
    Car replacement;
    Car(this.model, this.color);

class Immutable {
    final int id;
    final String name;
    final Car car;
    const Immutable(this.id, this.name, this.car);

    Immutable(1, 'Bob', Car('Audi', Color.Green))


 "id": 1,
 "name": "Bob",
 "car": {
  "modelName": "Audi",
  "color": "Color.Green"

Iterable based types handling #

Since Dart language has no possibility to create typed iterables dynamically, it's a bit of a challenge to create exact typed lists/sets/etc via reflection approach. Those types has to be declared explicitly.

For example List() will produce List<dynamic> type which can't be directly set to the concrete target field List<Car> for instance. So obvious workaround will be to cast List<dynamic> => List<Car>, which can be performed as List<dynamic>().cast<Car>().

In order to do so, we'll use Value Decorator Function inspired by Decorator pattern.

final iterableCarDecorator = (value) => value.cast<Car>();
final String json = '[{"modelName": "Audi", "color": "Color.Green"}]';

List<Car> myCarsList = JsonMapper.deserialize(json);
Set<Car> myCarsSet = JsonMapper.deserialize(json);

Basic iterable based generics using Dart built-in types like List<num>, List<Sring>, List<bool>, List<DateTime>, Set<num>, Set<Sring>, Set<bool>, Set<DateTime>, etc. supported out of the box.

For custom iterable types like List<Car> / Set<Car> you have to register value decorator function as showed in a code snippet above before using deserialization. This function will have explicit cast to concrete iterable type.

Enum based types handling #

Enum construction in Dart has a specific meaning, and has to be treated accordingly.

Enum declarations should not be annotated with @jsonSerializable, since they are not a classes technically, but a special built in types.

@JsonProperty(enumValues: Color.values)
Color color;

Each enum based class field has to be annotated as showed in a snippet above. Enum.values refers to a list of all possible enum values, it's a handy built in capability of all enum based types. Without providing all values it's not possible to traverse it's values properly.

Inherited classes derived from abstract / base class #

Please use complementary @Json(includeTypeName: true) annotation for subclasses derived from abstract or base class. This way dart-json-mapper will dump the concrete object type to the JSON output during serialization process. This ensures, that dart-json-mapper will be able to reconstruct the object with the proper type during deserialization process.

abstract class Business {
  String name;

@Json(includeTypeName: true)
class Hotel extends Business {
  int stars;


@Json(includeTypeName: true)
class Startup extends Business {
  int userCount;


class Stakeholder {
  String fullName;
  List<Business> businesses;

  Stakeholder(this.fullName, this.businesses);

// given
final jack = Stakeholder("Jack", [Startup(10), Hotel(4)]);

// when
JsonMapper.registerValueDecorator<List<Business>>((value) => value.cast<Business>());
final String json = JsonMapper.serialize(jack);
final Stakeholder target = JsonMapper.deserialize(json);

// then
expect(target.businesses[0], TypeMatcher<Startup>());
expect(target.businesses[1], TypeMatcher<Hotel>());

Using static JsonMapper.typeNameProperty you can specify suitable name for the json property, which will contain the object type:

JsonMapper.typeNameProperty = "objectType";

Custom based types handling #

For the very custom types, specific ones, or doesn't currently supported by this library, you can provide your own custom Converter class per each custom runtimeType.

/// Abstract class for custom converters implementations
abstract class ICustomConverter<T> {
  dynamic toJSON(T object, [JsonProperty jsonProperty]);
  T fromJSON(dynamic jsonValue, [JsonProperty jsonProperty]);

All you need to get going with this, is to implement this abstract class

class CustomStringConverter implements ICustomConverter<String> {
  const CustomStringConverter() : super();

  String fromJSON(dynamic jsonValue, [JsonProperty jsonProperty]) {
    return jsonValue;

  dynamic toJSON(String object, [JsonProperty jsonProperty]) {
    return '_${object}_';

And register it afterwards, if you want to have it applied for all occurrences of specified type


OR use it individually on selected class fields, via @JsonProperty annotation

@JsonProperty(converter: CustomStringConverter())
String title;

1.1.12 #

  • A convenience toJson/fromJson methods introduced

1.1.11 #

  • fix lint errors, update dependencies

1.1.10 #

  • fix for issue #15

1.1.9 #

  • proper fix for issue #9
  • refactoring

1.1.8 #

  • @JsonProperty.ignoreIfNull introduced, to skip null properties from processing

1.1.7 #

  • Issues #10, #11 has been fixed

1.1.6 #

  • Issue #9 has been fixed

1.1.5 #

  • Map<String, dynamic> easing methods toMap/fromMap introduced.

1.1.4 #

  • Issue #8 has been fixed

1.1.3 #

  • Documented use case with Inherited classes derived from abstract / base class

1.1.2 #

  • Issues #5, #6 has been fixed

1.1.1 #

  • Issue #4 has been fixed

1.1.0 #

  • Update build process, from now on relying on build_runner configured over build.yaml
  • Issues #2, #3 has been fixed

1.0.9 #

  • Added support for derived classes

1.0.8 #

  • Fixnum types Int32, Int64 support added

1.0.7 #

  • Iterable based types support enhanced

1.0.6 #

  • Set based types support added

1.0.5 #

  • Uint8List, BigInt types support added

1.0.4 #

  • Value decorators support enhanced

1.0.3 #

  • Value decorator introduced

1.0.2 #

  • Added some docs
  • Added test on ignored class field

1.0.1 #

  • Improved Support for Map<K, V> type
  • Added basic Support for dynamic type

1.0.0 #

  • Positional constructor parameters support
  • Support for Symbol, Map types
  • More tests added

0.1.3 #

  • Support Dart 2.0
  • Support latest reflectable library changes
  • Remove dependency on barback

0.1.2 #

  • Converters registry introduced
  • Error handling improved

0.1.1 #

  • Converter auto detection based on field type
  • Update pubspec for Dart 2.0

0.1.0 #

  • Update readme
  • Immutable classes serialization / deserialization support

0.0.9 #

  • Tiny update to fix pubspec & readme

0.0.8 #

  • Circular reference detection during serialization added

0.0.7 #

  • Support Lists of Enums, Dates, Numbers etc.
  • @JsonSerializable() => @jsonSerializable

0.0.6 #

  • build & watch scripts added as a tooling for development time

0.0.5 #

  • DateConverter & NumberConverter introduced
  • Parameters for custom converter introduced

0.0.4 #

  • Convert Enum values to string by default, to skip a disordered values drawback with indexed enum values.
  • Enum's does not have to be annotated, since almost all of them are parts of third party libraries w/o access for modification.
  • dateTimeConverter introduced

0.0.2 #

  • Remove dependency on dart:mirrors.

0.0.0 #

  • First published release.


library json_mapper.example;

import 'package:dart_json_mapper/annotations.dart';
import 'package:dart_json_mapper/converters.dart';
import 'package:dart_json_mapper/json_mapper.dart';

import 'example.reflectable.dart'; // Import generated code.

enum Color { Red, Blue, Green, Brown, Yellow, Black, White }

class Car {
  @JsonProperty(name: 'modelName')
  String model;

  @JsonProperty(enumValues: Color.values)
  Color color;

  Car(this.model, this.color);

  String toString() {
    return 'Car{model: $model, color: $color}';

class Person {
  List<String> skills = ['Go', 'Dart', 'Flutter'];

  @JsonProperty(name: 'last_promotion_date', ignore: true)
  DateTime lastPromotionDate;

  @JsonProperty(name: 'hire_date')
  DateTime hireDate = DateTime(2003, 02, 28);

  bool married = true;
  String name = "Forest";

  @JsonProperty(ignore: true)
  num salary;

  num dob;
  num age = 36;
  var lastName = "Gump";

  @JsonProperty(name: 'eye_color', enumValues: Color.values)
  Color eyeColor = Color.Blue;

  @JsonProperty(enumValues: Color.values, converter: enumConverterNumeric)
  Color hairColor = Color.Brown;

  List<Car> vehicles = [Car("Tesla", Color.Black), Car("BMW", Color.Red)];

  String get fullName => "${name} ${lastName}";


  String toString() {
    return 'Person{skills: $skills, lastPromotionDate: '
        '$lastPromotionDate, hireDate: $hireDate, married: $married, name: '
        '$name, salary: $salary, dob: $dob, age: $age, lastName: $lastName, '
        'eyeColor: $eyeColor, hairColor: $hairColor, vehicles: $vehicles}';

void main() {

  final String personJson = '''{
 "skills": [
 "hire_date": "2003-02-28",
 "married": true,
 "name": "Forest",
 "dob": null,
 "age": 36,
 "lastName": "Gump",
 "eye_color": "Color.Blue",
 "hairColor": 3,
 "vehicles": [
   "modelName": "Tesla",
   "color": "Color.Black"
   "modelName": "BMW",
   "color": "Color.Red"

  // Serialize

  // Deserialize

Use this package as a library

1. Depend on it

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

  dart_json_mapper: ^1.1.12

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter pub get

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

3. Import it

Now in your Dart code, you can use:

import 'package:dart_json_mapper/annotations.dart';
import 'package:dart_json_mapper/converters.dart';
import 'package:dart_json_mapper/errors.dart';
import 'package:dart_json_mapper/json_mapper.dart';
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 Oct 16, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21


Detected platforms: Flutter, web, other

No platform restriction found in libraries.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.3.1 <3.0.0
fixnum ^0.10.9 0.10.9
intl ^0.16.0 0.16.0
reflectable ^2.1.0 2.1.0
Transitive dependencies
args 1.5.2
async 2.4.0
build 1.1.6 1.2.0
build_config 0.4.1+1
build_daemon 2.1.0
build_resolvers 1.2.1
build_runner_core 3.1.1 4.1.0
built_collection 4.2.2
built_value 6.7.1
charcode 1.1.2
checked_yaml 1.0.2
code_builder 3.2.0
collection 1.14.12
convert 2.1.1
crypto 2.1.3
csslib 0.16.1
dart_style 1.2.10 1.3.1
front_end 0.1.21+1 0.1.27
glob 1.2.0
graphs 0.2.0
html 0.14.0+3
http 0.12.0+2
http_multi_server 2.1.0
http_parser 3.1.3
io 0.3.3
js 0.6.1+1
json_annotation 3.0.0
kernel 0.3.21+1 0.3.27
logging 0.11.3+2
matcher 0.12.5
meta 1.1.7
mime 0.9.6+3
node_interop 1.0.3
node_io 1.0.1+2
package_config 1.1.0
package_resolver 1.0.10
path 1.6.4
pedantic 1.8.0+1
pool 1.4.0
pub_semver 1.4.2
pubspec_parse 0.1.5
quiver 2.0.5
shelf 0.7.5
shelf_web_socket 0.2.3
source_span 1.5.5
stack_trace 1.9.3
stream_channel 2.0.0
stream_transform 0.0.19
string_scanner 1.0.5
term_glyph 1.1.0
timing 0.1.1+2
typed_data 1.1.6
watcher 0.9.7+12
web_socket_channel 1.1.0
yaml 2.2.0
Dev dependencies
analyzer ^0.37.1+1 0.37.1+1 0.38.5
build_runner any 1.6.9 1.7.2
build_test any
test any