Dson
dart library which converts Dart Objects into their JSON representation
Install / Use
/learn @dart-league/DsonREADME
DSON
DSON is a dart library which converts Dart Objects into their JSON representation.
This library was initially a fork from Dartson. Now it contains some differences:
-
Dartson uses custom transformers to convert objects to JSON. This produce faster and smaller code after dart2Js. Instead DSON uses [serializable]() and [built_mirrors]() libraries. This should produce code as fast and small as Dartson transformer.
-
DSON has the ability to serialize cyclical objects by mean of
expandparameter, which allows users to specify how deep in the object graph they want to serialize. -
DSON has the ability to exclude attributes for serialziation in two ways.
-
Using
@ignoreover every attribute. This make excluding attributes too global and hardcoded, so users can only specify one exclusion schema. -
Using
excludemap as parameter fortoJsonmethod. This is more flexible, since it allows to have many exclusion schemas for serialization.
-
-
DSON uses the annotation
@serializableinstead@entitywhich is used by Dartson.
Comparison with other libraries
https://github.com/drails-dart/dart-serialise
Tutorials

Configuration
1- Create a new dart project.
2- Add dependencies to pubspec.yaml
...
dependencies:
#...
dson: any # replace for latest version
#...
dev_dependencies:
#...
build_runner: any
build_web_compilers: any
#...
3- Create/edit bin/main.dart or web/main.dart and add the code shown
in any of the samples below.
4- Run either dart run build_runner build, or dart run build_runner watch, or dart run build_runner serve in the console
Convert objects to JSON strings
To convert objects to JSON strings you only need to use the toJson
function, annotate the object with @serializable and pass the object
to the toJson function as parameter:
library example.object_to_json; // this line is needed for the generator
import 'package:dson/dson.dart';
part 'object_to_json.g.dart'; // this line is needed for the generator
@serializable
class Person extends SerializableMap with _$PersonSerializable {
int? id;
String? firstName;
var lastName; //This is a dynamic attribute could be String, int, double, num, date or another type
double? height;
DateTime? dateOfBirth;
@SerializedName("renamed")
String? otherName;
@ignore
String? notVisible;
// private members are never serialized
String? _private = "name";
String? get doGetter => _private;
}
void main() {
_initMirrors();
Person object = Person()
..id = 1
..firstName = "Jhon"
..lastName = "Doe"
..height = 1.8
..dateOfBirth = DateTime(1988, 4, 1, 6, 31)
..otherName = "Juan"
..notVisible = "hallo";
String jsonString = toJson(object);
print(jsonString);
// will print: '{"id":1,"firstName":"Jhon","lastName":"Doe","height":1.8,"dateOfBirth":"1988-04-01T06:31:00.000","renamed":"Juan","doGetter":"name"}'
}
Converting objects to Maps
To convert objects to Maps you only need to use the toMap function,
annotate the object with @serializable and pass the object to
toMap function as parameter:
library example.object_to_map; // this line is needed for the generator
import 'package:dson/dson.dart';
part 'object_to_map.g.dart'; // this line is needed for the generator
@serializable
class Person extends SerializableMap with _$PersonSerializable {
int? id;
String? firstName;
var lastName; //This is a dynamic attribute could be String, int, duble, num, date or another type
double? height;
DateTime? dateOfBirth;
@SerializedName("renamed")
String? otherName;
@ignore
String? notVisible;
// private members are never serialized
String? _private = "name";
String? get doGetter => _private;
}
void main() {
_initMirrors();
Person object = Person()
..id = 1
..firstName = "Jhon"
..lastName = "Doe"
..height = 1.8
..dateOfBirth = DateTime(1988, 4, 1, 6, 31)
..otherName = "Juan"
..notVisible = "hallo";
Map map = toMap(object);
print(map);
// will print: '{id:1, firstName: Jhon, lastName: Doe, height: 1.8, dateOfBirth: 1988-04-01T06:31:00.000, renamed: Juan, doGetter: name}'
}
Serializing Cyclical Objects
To serialize objects that contains Cyclical References it would be
needed to use the annotation @cyclical. If this annotation is present
and the expand variable is not set then the non-primitive objects are
not going to be parsed and only the id (or hashmap if the object does
not contains id) is going to be present. Let’s see next example:
library example.serialize_cyclical; // this line is needed for the generator
import 'package:dson/dson.dart';
part 'serialize_cyclical.g.dart'; // this line is needed for the generator
@serializable
@cyclical
class Employee extends SerializableMap with _$EmployeeSerializable {
@uId int? key;
String? firstName;
String? lastName;
Address? address;
Employee? manager;
}
@serializable
@cyclical
class Address extends SerializableMap with _$AddressSerializable {
@uId int? key;
String? street;
String? city;
String? country;
String? postalCode;
Employee? owner;
}
void main() {
_initMirrors();
var manager = Employee()
..key = 1
..firstName = 'Jhon'
..lastName = 'Doe';
manager.address = Address()
..key = 1
..street = 'some street'
..city = 'Miami'
..country = 'USA'
..owner = manager;
var employee = Employee()
..key = 2
..firstName = 'Luis'
..lastName = 'Vargas'
..manager = manager;
employee.address = Address()
..key = 2
..street = 'some street'
..city = 'Miami'
..country = 'USA'
..owner = employee;
print(toJson(employee)); //will print: '{"id":2,"firstName":"Luis","lastName":"Vargas","address":{"id":2},"manager":{"id":1}}'
print(toJson(employee.address)); // will print: '{"id":2,"street":"some street","city":"Miami","country":"USA","owner":{"id":2}}'
// depth is a optional parameter that could be a list that should contains strings or Maps<String, Map>
print(toJson(employee, expand: ['address']));
/* will print:
'{"id":2,"firstName":"Luis","lastName":"Vargas",'
'"address":{"id":2,"street":"some street","city":"Miami","country":"USA","owner":{"id":2}},'
'"manager":{"id":1}}'
*/
print(toJson(employee, expand: [{'manager': ['address']}, 'address']));
/* will print:
'{"id":2,"firstName":"Luis","lastName":"Vargas",'
'"address":{"id":2,"street":"some street","city":"Miami","country":"USA",'
'"owner":{"id":2}},'
'"manager":{"id":1,"firstName":"Jhon","lastName":"Doe",'
'"address":{"id":1,"street":"some street","city":"Miami","country":"USA","owner":{"id":1}}}}');
*/
}
as you can see employee has an address, and the address has an owner of
type Employee. If the property id is not present in the object then it
is going to take the hashcode value from the object as reference. And
finally, the expand parameter passed to serialize function tells
serializer how deep you want to go throw the reference. This help us not
only to avoid cyclical reference, but to determine what referenced
objects should be serialized.
The same applies for lists:
library example.serialize_cyclical_list; // this line is needed for the generator
import 'package:dson/dson.dart';
part 'serialize_cyclical_list.g.dart'; // this line is needed for the generator
@serializable
@cyclical
class Student extends SerializableMap with _$StudentSerializable {
int? id;
String? name;
List<Course>? courses;
}
@serializable
@cyclical
class Course extends SerializableMap with _$CourseSerializable {
int? id;
DateTime? beginDate;
List<Student>? students;
}
void main() {
// by the moment is needed to initialize the mirrors manually
_initMirrors();
var student1 = Student()
..id = 1
..name = 'student1',
student2 = Student()
..id = 2
..name = 'student2',
student3 = Student()
..id = 3
..name = 'student3',
course1 = Course()
..id = 1
..beginDate = DateTime.utc(2015, 1, 1)
..students = [student1, student2],
course2 = Course()
..id = 2
..beginDate = DateTime.utc(2015, 1, 2)
..students = [student2, student3],
course3 = Course()
..id = 3
..beginDate = DateTime.utc(2015, 1, 3)
..students = [student1, student3];
student1.courses = [course1, course3];
student2.courses = [course1, course2];
student3.courses = [course2, course3];
var students = [student1, student2, student3];
print(toJson(students));
print(toJson(student1)); // will print: '{"id":1,"name":"student1","courses":[{"id":1},{"id":3}]}'
print(toJson(student1, expand: ['courses']));
/* will print:
'{'
'"id":1,'
'"name":"student1",'
'"courses":['
'{"id":1,"beginDate":"2015-01-01T00:00:00.000Z","students":[{"id":1},{"id":2}]},'
'{"id":3,"beginDate":"2015-01-03T00:00:00.000Z","students":[{"id":1},{"id":3}]}'
']'
'}');
*/
print(toJson(student1.courses));
/* will print:
'['
'{"id":1,"beginDate":"2015-01-01T00:00:00.000Z","students":[{"id":1},{"id":2}]},'
'{"id":3,"beginDate":"2015-01-03T00:00:00.000Z","students":[{"id":1},{"id":3}]}'
']');
*/
print(toJson(student2.courses, expand: ['students']));
/* will print:
'['
'{"id":1,"beginDate":"2015-01-01T00:00:00.000Z","students":['
'{"id":1,"name":"student1","courses":[{"id":1},{"id":3}]},'
'{"id":2,"name":"studen
