Skip to content

Serializing objects

Luis Vargas edited this page Mar 13, 2015 · 1 revision

Serialize an object is the action of converting the object to JSON string. To do this you only need to use the serialize function. For example:

library example;

import 'package:dson/dson.dart';

@MirrorsUsed(targets:const['example'],override:'*')
import 'dart:mirrors';

class Person {
  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;

  @Property("renamed")
  String otherName;
  

  @ignore
  String notVisible;

  // private members are never serialized
  String _private = "name";

  String get doGetter => _private;
}

void main() {
  Person object = new Person()
    ..id = 1
    ..firstName = "Jhon"
    ..lastName = "Doe"
    ..height = 1.8
    ..dateOfBirth = new DateTime(1988, 4, 1, 6, 31)
    ..otherName = "Juan"
    ..notVisible = "hallo";

  String jsonString = serialize(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"}'
}