jsonable 0.1.0+1

  • Readme
  • Changelog
  • Example
  • Installing
  • 76

Jsonable #

(deprecated of 0.0.2+2) if you are interested in Jsoable with reflect read here

Jsonable is a library that deals with offering a simple way to manage dart classes fromJson and toJson, allowing the transpiration from dart to json. One of the main objectives and the philosophy of Jsoanble, is to remove the generated code making any object convertible into Json.

In the first version of Jsonable reflection was used, but this is not supported in the AOT compiler of dart.

Jsonable does not use reflection or even generated code.

how to use? #

Jsonable makes available a mixin mixin Jsonable within this mixin is the management of the Json scheme. only by extending our class with the mixin, the class gets the necessary methods, but if we don't indicate the members of json, using "toJson" or "toMap" will be an empty Map / string. ({})

let's see an example:

import "package:jsonable/jsonable.dart";

class Person with Jsonable {
 JString name;
 JString surname;
  Person({String name, String surname}) {
    this.name = this.jString("name", initialValue: name);
    this.surname = this.jString("surname", initialValue: surname);
  }
}

main() {
  var p = Person(name: "Nico", surname: "Spina");
  print(p.toJson());
  // output: {"name":"Nico","surname":"Spina"}
}

Jsonable implements different types to represent the whole Json structure:

  • JString
  • JNum
  • JBool
  • JClass<E extends Jsonable>
  • JList<E>
  • JDynamic
  • JMap

Jsonable records these types and serializes and deserializes the structure based on these types

The functions provided by Jsonable:

  • JClass<E> jClass<E extends Jsonable>(keyname, JsonableConstructor constructor, {E initialValue})

    It returns a JClass is JType<Jsonable> in the generic of this type, extends Jsonable, moreover it requires the constructor a simple function that returns an instance of that type. Note: it will be instantiated immediately to the declaration if InitialValue is null

  • JList<E> jList<E>(dynamic keyname, {List<E> initialValue, JsonableConstructor constructor})

aJList represents a List that can contain any value, you can iterate overJList and you don't need to access the value via ".value", in this type the constructor parameter becomes mandatory if you are using a Jsonable as generic are not allowed types of data other than: bool, string, num, int, double, map, list,

  • JString jString(dynamic keyname, {String initialValue})

    Return a JType <String> then manage a String type in the schema with fromJson will assign the value only if it is a String, in toJson it will assign a String, you can assign only String values via ".value"

  • JCool jBool(dynamic keyname, {bool initialValue})

    Return a JType <bool> then manage a bool type in the schema with fromJson will assign the value only if it is a bool, in toJson it will assign a bool, you can assign only bool values via ".value"

  • JNum jNum(dynamic keyname, {num initialValue})

    Return a JType <num> then manage a num type in the schema with fromJson will assign the value only if it is a num, in toJson it will assign a num, you can assign only num values via ".value"

  • JMap jMap(dynamic keyname, {Map initialValue})

    Return a JType <Map<E,R>> then manage a Map<E,R> type in the schema with fromJson will assign the value only if it is a Map<E,R>, in toJson it will assign a Map<E,R>, you can assign only Map<E,R> values via ".value"

  • JDynamic jDynamic(dynamic keyname, {dynamic initialValue})

    Return a JType <dynamic> then manage a dynamic type in the schema with fromJson will assign the value only if it is a dynamic, in toJson it will assign a dynamic, you can assign only dynamic values via ".value"

  • dynamic jOnce(keyname, Jsonable value) *experimental

    jOnce Returns the same value that passes in the value, the value you pass:

    it is inserted inside the Json schema, in a JClass that is not instantiated, further.

    This function is very useful when you are in a context like Flutter,

    where objects are called only in the widget build.

    Jonce returns your widget, without compromising it as long as the widget uses Jsonable

Validation #

From the Jsoanble 0.1.0 version, support for json schema validation has been introduced

Validation is done using "rules" that are made available to the "Rules" class.

The Rules are applied to the single field and validate the single field.

Each field, then every JType has the validate() method which returns a list of elements that are exceptions RuleException every rule has its exception and all extend RuleException, following a small example where we apply the rules:

import 'package:jsonable/jsonable.dart';

class Person with Jsonable {
  JString name;
  JString surname;
  JNum years;
  Person() {
    name = this.jString("name", rules: [
      Rules.max(12),
      Rules.min(4),
    ]);
    surname = this.jString("surname", rules: [
      Rules.min(4),
      Rules.max(12),
    ]);

    years = this.jNum("years", rules: [
      /// If this rule fails, you will get this error in the error list: GteRuleExcpetion
      /// To get the list of errors call .validate() (method of Jsoanble object)
      Rules.min(18, message: "My personal error message!"),
      Rules.max(99),
    ]);
  }
}

the Jsonable mixin also provides a validated method, in this case it will returnMap <String, List <RuleException>> where the keys (String) are the names of the fields, while the values are lists of the exceptions of the single value , the validate () method within the mixin calls the validates of each of its internal elements.

Custom Rules #

Surely it may be interesting to create your own Rule, in order to cover a given behavior that the rules do not support. To create your own rule you can use the Rules.customRule() method.

This method accepts two necessary and mandatory parameters to correctly create your rule, see an example:

// signature customRule;  
/*
Rule customRule(
      bool Function(JType) test, RuleException Function(JType) exption) */

import 'package:jsonable/jsonable.dart';

var myPersonalRule = Rules.customRule((JType value) {
  if (value is JString) {
    if (value.getString() != "Nico") {
      return true;
    }
  }

  return false;
}, (JType value) => RuleException("${value.keyname} oh No!!"));

class Person with Jsonable {
  JString name;

  Person() {
    this.name = this.jString("name", rules: [myPersonalRule]);
  }
}

Performance #

in this 0.0.2 release I had particular attention to performance: Jsonable is less than 50% slower than native (generated). This test has not yet been made a benchmark with written tests. Tests were made by timing, the result was:

Note: I used dartVm not AOT, test with jsonable: 0.0.2

Conclusion #

If you want you can support the development by offering me a coffee: paypal

If you can't buy coffee, you can always leave me a star on github.

thanks!

0.1.0 #

  • add add support for JMap for Map\<dynamic, dyanmic\> and Map of Jsonable: Map<String, Jsoanble>

      class Person with Jsonable {
        JMap tags;
        JMap<String, Contact> contacts;
        Person() {
          this.tags = jMap("tags");
          this.contacts = jMap<String, Contact>("contacts", builder: () => Contact());
        }
      }
    
      class Contact with Jsonable {
        JString name;
        JString number;
        Contact() {
          name = jString("name");
          number = jString("number");
        }
      }
    
  • add jDynamic new JType for dynamic

  • New add support for validation field of Jsonable object (see readme)

  • Breaking change delete support Jsonable with reflection use dson

  • add setter and getter value

    • void setValue(E value) - set value within JType
  • E getValue; - get value in JType

  • addevery JType has access to "value" even in a more specific way

    • setString(String value) / String getString()
    • setNum(num value) / num getNum()
    • setBool(bool value) / bool getBool()
  • Breaking Change removed (experimental) operator "<<" and operator ">>"

0.0.2+2 #

  • (experimental) add JType operator "<<" for set value internal Jtype and operator ">>" for get value internal Jtype
  • add Jsonable operator "[]"
  • performance improvement
  • deprecation old Jsonable reflect if you use reflection use this pack: dson
  • start of experiments with flutter and auto-form (soon with a new flutter package)
  • add example for benchmark

0.0.2 #

Breaking change.

With the 0.0.1 management I started development with the reflection of Dart. This resulted in problems with AOT and consequently also with flutter. In version 0.0.2 all the APIs based on reflection in jsonable / withReflect have been moved

Announcements: 0.0.2 I set out to remove the generation of dart code from my projects, it's a practice I don't like. So in version 0.0.2 I start the creation of a module that is without generation and without reflection.

For more information read here.

0.0.1 #

  • frist publication. read: Readme.md

example/README.md

All examples! #

generic #
  • lib/simple_class.dart a very simple example with Jsonable.
  • lib/operator_jnum.dart an example showing: Jnum support operator ==
validation and rules #
  • /lib/exmaple_validation/custom_rule.dart an example with a custom rule

I have not reported all the examples, in this package the examples are tested.

To see all the examples go to github

Use this package as a library

1. Depend on it

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


dependencies:
  jsonable: ^0.1.0+1

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:jsonable/jsonable.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
61
Health:
Code health derived from static analysis. [more]
85
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
76
Learn more about scoring.

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

  • Dart: 2.7.0
  • pana: 0.13.1+4

Health suggestions

Fix lib/src/validator/rules.dart. (-3.93 points)

Analysis of lib/src/validator/rules.dart reported 8 hints, including:

line 122 col 13: DO use curly braces for all flow control structures.

line 150 col 11: DO use curly braces for all flow control structures.

line 152 col 11: DO use curly braces for all flow control structures.

line 212 col 44: DO use curly braces for all flow control structures.

line 221 col 11: DO use curly braces for all flow control structures.

Fix lib/src/typing/CJnum.dart. (-3.45 points)

Analysis of lib/src/typing/CJnum.dart reported 7 hints, including:

line 6 col 42: Use = to separate a named parameter from its default value.

line 15 col 7: DO use curly braces for all flow control structures.

line 17 col 7: DO use curly braces for all flow control structures.

line 22 col 7: DO use curly braces for all flow control structures.

line 24 col 7: DO use curly braces for all flow control structures.

Fix lib/src/typing/CJlist.dart. (-1.99 points)

Analysis of lib/src/typing/CJlist.dart reported 4 hints:

line 30 col 23: Use = to separate a named parameter from its default value.

line 152 col 3: Avoid return types on setters.

line 175 col 3: Avoid return types on setters.

line 188 col 3: Avoid return types on setters.

Fix additional 8 files with analysis or formatting issues. (-6.97 points)

Additional issues in the following files:

  • lib/jsonable.dart (3 hints)
  • lib/src/typing/CJbool.dart (3 hints)
  • lib/src/typing/CJstring.dart (3 hints)
  • lib/src/mixin_jsonable.dart (1 hint)
  • lib/src/scheme/fx.dart (1 hint)
  • lib/src/typing/CJclass.dart (1 hint)
  • lib/src/typing/CJdynamic.dart (1 hint)
  • lib/src/typing/CJmap.dart (1 hint)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
Dev dependencies
benchmark_harness any
test any
test_coverage ^0.3.0