问题描述
我上课
class Person{
String _fn, _ln;
Person(this._fn, this._ln);
}
有没有一种方法来获取变量列表,然后对其进行序列化?本质上,我想制作toJson,但我想使其具有足够的通用性,以使键为变量名,而值为变量名的值.
Is there a way to get a list of variables and then serialize it? Essentially i want to make a toJson, but i wanted to have it generic enough such that key is the variable name, and the value is the value of the variable name.
在javascript中,它类似于:
In javascript it would be something like:
var myObject = {}; //.... whatever you want to define it as..
var toJson = function(){
var list = Object.keys(myObject);
var json = {};
for ( var key in list ){
json[list[key]] = myObject[list[key]] ;
}
return JSON.stringify(json);
}
推荐答案
Dart没有内置的序列化功能. pub.dartlang.org提供了几种具有不同策略的软件包.有些使用镜像,这对客户端应用程序有害,因为它会导致JS输出大小很大.新的reflectable
软件包取代了mirrors
,没有任何缺点,但是我不知道序列化软件包是否已经移植以使用它.也有一些使用代码生成的软件包.
Dart doesn't have a built in functionality for serialization. There are several packages with different strategies available at pub.dartlang.org. Some use mirrors, which is harmful for client applications because it results in big or huge JS output size. The new reflectable
packages replaces mirrors
without the disadvantage but I don't know if serialization packages are already ported to use it instead. There are also packages that use code generation.
有一个带答案的问题,列出了可用的解决方案.我回来的时候会去找它.
There is a question with an answer that lists available solutions. I'll look it up when I'm back.
这篇关于获取dart类的所有变量以进行json编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!