Search code examples
serializationdartdart-mirrors

how to use serialization package


I want to convert my class to a Map so I'm using Serialization package. From the example it looks simple:

var address = new Address();
 address.street = 'N 34th';
 address.city = 'Seattle';
 var serialization = new Serialization()
     ..addRuleFor(Address);
 Map output = serialization.write(address);

I expect to see an output like {'street' : 'N 34th', 'city' : 'Seattle'} but instead it just output something I-don't-know-what-that-is

{"roots":[{"__Ref":true,"rule":3,"object":0}],"data":[[],[],[],[["Seattle","N 34th"]]],"rules":"{\"roots\":[{\"__Ref\":true,\"rule\":1,\"object\":0}],\"data\":[[],[[{\"__Ref\":true,\"rule\":4,\"object\":0},{\"__Ref\":true,\"rule\":3,\"object\":0},{\"__Ref\":true,\"rule\":5,\"object\":0},{\"__Ref\":true,\"rule\":6,\"object\":0}]],[[],[],[\"city\",\"street\"]],[[]],[[]],[[]],[[{\"__Ref\":true,\"rule\":2,\"object\":0},{\"__Ref\":true,\"rule\":2,\"object\":1},\"\",{\"__Ref\":true,\"rule\":2,\"object\":2},{\"__Ref\":true,\"rule\":7,\"object\":0}]],[\"Address\"]],\"rules\":null}"}


Solution

  • Serialization is not supposed to create human-readable output. Maybe JSON output is more what you look for:

    import dart:convert;
    
    {
    var address = new Address();
      ..address.street = 'N 34th';
      ..address.city = 'Seattle';
    
    var encoded = JSON.encode(address, mirrorJson);
    }
    
    Map mirrorJson(o) { 
      Map map = new Map();
      InstanceMirror im = reflect(o);
      ClassMirror cm = im.type;
      var decls = cm.declarations.values.where((dm) => dm is VariableMirror);
      decls.forEach((dm) {
        var key = MirrorSystem.getName(dm.simpleName);
        var val = im.getField(dm.simpleName).reflectee;
        map[key] = val;
      });
    
      return map;
    }