gpt4 book ai didi

serialization - 如何使用序列化包

转载 作者:行者123 更新时间:2023-12-03 02:51:45 25 4
gpt4 key购买 nike

我想将我的类(class)转换为Map,所以我使用的是Serialization包。从该示例看起来很简单:

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

我希望看到类似于 {'street' : 'N 34th', 'city' : 'Seattle'}的输出,但它只是输出一些我不知道那是什么的东西
{"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}"}

最佳答案

序列化不应创建人类可读的输出。也许JSON输出更符合您的需求:

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

关于serialization - 如何使用序列化包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21271438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com