dart_json_mapper 0.1.3

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 81

dart-json-mapper

pub package

Serialize / Deserialize Dart Objects to / from JSON

This package allows programmers to annotate Dart classes in order to serialize / deserialize them from / to JSON.

Basic setup

Library has 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.

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

lib/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;

  // Important! Constructor must not have any required parameters.
  MyData([this.a, this.b, this.c]);
}

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

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

> pub run dart_json_mapper:build lib/main.dart

where lib/main.dart should be replaced by the root library of the program for which you wish to generate code. You can generate code for several programs in one step; for instance, to generate code for a set of test files in test, this would typically be pub run dart_json_mapper:build test/*_test.dart. 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 dart_json_mapper:watch lib/main.dart

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
  • This is it, basic setup is done.

Example

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

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

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

print(
  JsonMapper.serialize(
    new Immutable(id: 1, name: 'Bob', car: new Car('Audi', Color.Green))
  )
);

Output:

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

Why is this library exists?

When there are so many alternatives out there

It would be nice to have a Json serialization/deserialization library

  • Compatible with all Dart platforms, including Flutter and Web platforms.
  • No need to extend target classes from any mixins/base/abstract classes to keep code cleaner
  • Clean and simple setup, transparent and straightforward usage with no heavy maintanance involved
  • No extra boilerplate code involved
  • Custom converters support per each target class field

But, as of today we have...

| Name | Web + Flutter support | Concerns | | ----------- |:-----------------------:|:-----------|
|json_object_lite| yes | Target class has to be inherited from JsonObjectLite + boilerplate code | |jaguar_serializer| yes | Tons of boilerplate, personal serializer generated per each target class, unnecessary abstraction - "model"| |nomirrorsmap| yes | Cumbersome usage| |dson_core| no | | |dson| yes | Requires target class to be inherited from mixin + too much different unobvious annotations, like @ignore, @cyclical, @uid, etc| |dartson| no | | |json_god| no | | |jaguar_json| no | | |serializer_generator| no | | |dynamo| yes |Produces JSON output with type information injected in it| |serialization|yes |Cumbersome configuration and setup, will require continuous maintenance| |serializable| yes |Requires target class to be inherited from mixin, no custom logic allowed| |json_annotation|yes |Depends on json_serializable which is not compatible with Flutter| |json_serializable| no || |json_mapper| no || |built_value| yes |Over engineered solution, boilerplate, yes it's auto generated, but it is still boilerplate! enforces Immutability for all models, imply own patterns on your code base, too much responsibility in one library |

Feature requests and bug reports

Please file feature requests and bugs using the github issue tracker for this repository.

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.

example/example.dart

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 }

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

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

  Car([this.model, this.color]);

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

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

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

  @JsonProperty(name: 'hire_date')
  DateTime hireDate = new 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 = [
    new Car("Tesla", Color.Black),
    new Car("BMW", Color.Red)
  ];

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

  Person();

  @override
  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() {
  initializeReflectable();

  final String personJson = '''{
 "skills": [
  "Go",
  "Dart",
  "Flutter"
 ],
 "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
  print(JsonMapper.serialize(new Person()));

  // Deserialize
  print(JsonMapper.deserialize(personJson, Person));
}

Use this package as a library

1. Depend on it

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


dependencies:
  dart_json_mapper: ^0.1.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages 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';
  
Version Uploaded Documentation Archive
0.1.3 Aug 19, 2018 Go to the documentation of dart_json_mapper 0.1.3 Download dart_json_mapper 0.1.3 archive
0.1.2 Jul 27, 2018 Go to the documentation of dart_json_mapper 0.1.2 Download dart_json_mapper 0.1.2 archive
0.1.1 Jul 25, 2018 Go to the documentation of dart_json_mapper 0.1.1 Download dart_json_mapper 0.1.1 archive
0.1.0 Jun 24, 2018 Go to the documentation of dart_json_mapper 0.1.0 Download dart_json_mapper 0.1.0 archive
0.0.9 Jun 20, 2018 Go to the documentation of dart_json_mapper 0.0.9 Download dart_json_mapper 0.0.9 archive
0.0.8 Jun 1, 2018 Go to the documentation of dart_json_mapper 0.0.8 Download dart_json_mapper 0.0.8 archive
0.0.7 May 31, 2018 Go to the documentation of dart_json_mapper 0.0.7 Download dart_json_mapper 0.0.7 archive
0.0.6 May 30, 2018 Go to the documentation of dart_json_mapper 0.0.6 Download dart_json_mapper 0.0.6 archive
0.0.5 May 29, 2018 Go to the documentation of dart_json_mapper 0.0.5 Download dart_json_mapper 0.0.5 archive
0.0.4 May 28, 2018 Go to the documentation of dart_json_mapper 0.0.4 Download dart_json_mapper 0.0.4 archive

All 14 versions...

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

We analyzed this package on Aug 19, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.11.8

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in libraries.

Suggestions

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 of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.12.0 <3.0.0
analyzer ^0.32.0 0.32.4
build ^0.12.0 0.12.7+3
build_config ^0.3.0 0.3.1+2
build_runner ^0.10.0 0.10.1+1
intl ^0.15.6 0.15.7
reflectable ^2.0.3 2.0.3
Transitive dependencies
args 1.5.0
async 2.0.8
build_resolvers 0.2.2+2
build_runner_core 0.3.1+4
built_collection 3.1.3
built_value 5.5.5 6.0.0
charcode 1.1.2
cli_util 0.1.3+2
code_builder 3.1.2
collection 1.14.11
convert 2.0.2
crypto 2.0.6
csslib 0.14.5
dart_style 1.1.3
fixnum 0.10.8
front_end 0.1.4
glob 1.1.7
graphs 0.1.2+1
html 0.13.3+3
http 0.11.3+17
http_multi_server 2.0.5
http_parser 3.1.3
io 0.3.3
json_annotation 1.1.0
kernel 0.3.4
logging 0.11.3+2
matcher 0.12.4
meta 1.1.6
mime 0.9.6+2
package_config 1.0.5
package_resolver 1.0.4
path 1.6.2
plugin 0.2.0+3
pool 1.3.6
pub_semver 1.4.2
pubspec_parse 0.1.2+2
quiver 2.0.0+1
shelf 0.7.3+3
shelf_web_socket 0.2.2+4
source_span 1.4.1
stack_trace 1.9.3
stream_channel 1.6.8
stream_transform 0.0.14+1
string_scanner 1.0.4
typed_data 1.1.6
utf 0.9.0+5
watcher 0.9.7+10
web_socket_channel 1.0.9
yaml 2.1.15
Dev dependencies
build_test ^0.10.0
test ^1.3.0