2

I have a class

class Person{
  String _fn, _ln;
  Person(this._fn, this._ln);
}

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.

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);
}
Fallenreaper
  • 10,222
  • 12
  • 66
  • 129

1 Answers1

1

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Ahh ok. I'll just make a Model to pass around then instead and use that. – Fallenreaper Jan 15 '16 at 20:35
  • 1
    To send it between client and server you need a serialization format like JSON (or protobuf, ...). Where you can pass the object instance itself you should do that without serialization/deserialization anyway. – Günter Zöchbauer Jan 15 '16 at 20:37
  • 1
    http://stackoverflow.com/questions/20024298/add-json-serializer-to-every-model-class seems a bit outdated but I haven't found a better one. – Günter Zöchbauer Jan 15 '16 at 20:40
  • 1
    I will mark this as the answer, but my goal is for database fetches or inserts.... I want to be able to serialize the object for data to save to a db so when i pull the data, i can re instantiate the object client side for passing around. – Fallenreaper Jan 18 '16 at 12:45