更新时间:2022-05-24 01:55:51
现在,***的选择是使用 Smoke 图书馆。
For now, the best option is probably to use the Smoke library.
这是镜像功能,但具有基于镜像和基于Codegen的实现。它由PolymerDart团队编写,因此它接近官方,我们将获得。
It's a subset of the Mirrors functionality but has both a Mirrors-based and a Codegen-based implementation. It's written by the PolymerDart team, so it's as close to "Official" as we're going to get.
在开发时,它将使用基于镜像的编码/解码;
While developing, it'll use the Mirrors-based encoding/decoding; but for publishing you can create a small transformer that will generate code.
Seth Ladd建立了此处的代码示例,我稍微扩展支持子对象:
Seth Ladd created a code sample here, which I extended slightly to support child-objects:
abstract class Serializable {
static fromJson(Type t, Map json) {
var typeMirror = reflectType(t);
T obj = typeMirror.newInstance(new Symbol(""), const[]).reflectee;
json.forEach((k, v) {
if (v is Map) {
var d = smoke.getDeclaration(t, smoke.nameToSymbol(k));
smoke.write(obj, smoke.nameToSymbol(k), Serializable.fromJson(d.type, v));
} else {
smoke.write(obj, smoke.nameToSymbol(k), v);
}
});
return obj;
}
Map toJson() {
var options = new smoke.QueryOptions(includeProperties: false);
var res = smoke.query(runtimeType, options);
var map = {};
res.forEach((r) => map[smoke.symbolToName(r.name)] = smoke.read(this, r.name));
return map;
}
}
目前,不支持获取通用类型信息(例如:支持List)在Smoke中;但我在这里提出了一个案例:
Currently, there is no support to get generic type information (eg. to support List) in Smoke; however I've raised a case about this here:
https://code.google.com/p/dart/issues/detail?id=20584
直到这个问题实现了,一个好的实现你想要的是不是真的可行;但我希望它会很快实施;因为做一些像JSON序列化这样基本的东西就取决于它!
Until this issue is implemented, a "good" implementation of what you want is not really feasible; but I'm hopeful it'll be implemented soon; because doing something as basic as JSON serialisation kinda hinges on it!
Alan Knight也在编写一个Serialization包,但是我发现它缺乏对简单的支持将数据时间转换为字符串,并且解决方案对于这样基本的东西显得相当冗长。
Alan Knight is also working on a Serialisation package, however I found it to lack support for things as simple as converting datetimes to strings, and the solution seemed rather verbose for something so basic.
现在,在我自己的项目中,我已经使用代码创建我们的json序列化toMap和fromMap方法的形式),因为我们已经有了服务器端的类的C#版本。如果时间允许,我想整理这些代码,并制作一个NuGet包(它支持嵌套对象,数组,排除属性等)。
For now, in my own project, I've gone with codegenning our json serialisation (in the form of toMap and fromMap methods) since we would already have C# versions of our classes for the server side. If time allows, I'd like to tidy those code up and make a NuGet package (it supports nested objects, arrays, excluding properties, etc.).