質問

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}"}

役に立ちましたか?

解決

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;
}   

他のヒント

The new Address() creates a full prototype object which is what you are seeing. That being said, they could have done something to avoid part of those, but if you want to restore the object just the way it is, that's necessary.

To see the full content of an object you use the for() instruction in this way:

for(obj in idx) alert(obj[idx]);

You'll see that you get loads of data this way. Without the new Address() it would probably not be that bad.

Serialization won't help you here...

You might give a try to JsonObject library, and maybe go through this in depth explanation how to do what you are trying to do using mirrors.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top