platform/packages/json_god
2021-05-15 14:01:47 +08:00
..
example Updated json_god 2021-05-15 09:31:17 +08:00
lib Updated json_god 2021-05-15 09:31:17 +08:00
test Publish angle3_json_god 2021-05-14 20:24:45 +08:00
.gitignore Publish angle3_json_god 2021-05-14 20:24:45 +08:00
.travis.yml Updated package client 2021-03-08 00:02:53 +08:00
analysis_options.yaml Added json_god package 2021-03-07 23:56:09 +08:00
AUTHORS.md Publish angle3_json_god 2021-05-14 20:24:45 +08:00
CHANGELOG.md Updated json_god 2021-05-15 09:31:17 +08:00
LICENSE Publish angle3_json_god 2021-05-14 20:24:45 +08:00
pubspec.yaml Updated json_god 2021-05-15 09:31:17 +08:00
README.md Publish route 2021-05-15 14:01:47 +08:00

angel3_json_god

version Null Safety Gitter

License

The new and improved definitive solution for JSON in Dart. It supports synchronously transform an object into a JSON string and also deserialize a JSON string back into an instance of any type.

Installation

dependencies:
    angel3_json_god: ^4.0.0

Usage

It is recommended to import the library under an alias, i.e., god.

import 'package:angel3_json_god/angel3_json_god.dart' as god;

Serializing JSON

Simply call god.serialize(x) to synchronously transform an object into a JSON string.

Map map = {"foo": "bar", "numbers": [1, 2, {"three": 4}]};

// Output: {"foo":"bar","numbers":[1,2,{"three":4]"}
String json = god.serialize(map);
print(json);

You can easily serialize classes, too. JSON God also supports classes as members.


class A {
    String foo;
    A(this.foo);
}

class B {
    late String hello;
    late A nested;
    B(String hello, String foo) {
      this.hello = hello;
      this.nested =  A(foo);
    }
}

main() {
    print(god.serialize( B("world", "bar")));
}

// Output: {"hello":"world","nested":{"foo":"bar"}}

If a class has a toJson method, it will be called instead.

Deserializing JSON

Deserialization is equally easy, and is provided through god.deserialize.

Map map = god.deserialize('{"hello":"world"}');
int three = god.deserialize("3");

Deserializing to Classes

JSON God lets you deserialize JSON into an instance of any type. Simply pass the type as the second argument to god.deserialize.

If the class has a fromJson constructor, it will be called instead.

class Child {
  String foo;
}

class Parent {
  String hello;
  Child child =  Child();
}

main() {
  God god =  God();
  Parent parent = god.deserialize('{"hello":"world","child":{"foo":"bar"}}', Parent);
  print(parent);
}

Any JSON-deserializable classes must initializable without parameters. If Foo() would throw an error, then you can't use Foo with JSON.

This allows for validation of a sort, as only fields you have declared will be accepted.

class HasAnInt { int theInt; }

HasAnInt invalid = god.deserialize('["some invalid input"]', HasAnInt);
// Throws an error

An exception will be thrown if validation fails.