Can I automatically serialize a Dart object to sen

2019-02-27 01:21发布

问题:

I just saw that there are some libraries for running a Dart web server, like Start. So I was thinking something like this.. If both client and server code is written in Dart, is it possible to send "Dart objects" via websockets (or normal REST for that matter) so that the type information remains on the other end? Or do I need to serialize/deserialize via JSON or something similar on the way? Or am I over thinking things here?

regards Oskar

回答1:

You will need to serialize the Dart object somehow. You can try JSON, or you can try the heavy-duty serialization package.

There is no fully automatic JSON serialization for custom Dart classes. You will need to add a custom toJson serializer and create some sort of fromJson constructor.

e.g. if you had a Person class, you could do something like this:

import 'dart:json' as json;

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  Person.fromJson(String json) {
    Map data = json.parse(json);
    name = data['name'];
    age = data['age'];
  }

  Map toJson() {
    return {'name': name, 'age': age};
  }
}

Note: the fromJson is just a convention. You will need to call it somehow, there is no built-in mechanism to take an arbitrary JSON string and call the right constructors on your custom object.

As mentioned above, the serialization package is more heavy weight, but much more full featured. Here is an example from its docs:

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

and

 // uses serialization
 var serialization = new Serialization()
   ..addRuleFor(address,
       constructor: "create",
       constructorFields: ["number", "street"],
       fields: ["city"]);


回答2:

You can use the 'exportable' package to render your class to JSON or a map in a more declarative fashion.

import 'package:exportable/exportable.dart';

class Product extends Object with Exportable
{
  @export String ProductName;
  @export num UnitPrice;
  @export bool Discontinued;
  @export num UnitsInStock;

  Product(this.ProductName, this.UnitPrice, this.Discontinued, this.UnitsInStock);  
}

Product prod = new Product("First", 1.0, false, 3 );
var json = prod.toJson();  // {"ProductName":"First","UnitPrice":1.0,"Discontinued":false,"UnitsInStock":3}