Skip to content Skip to sidebar Skip to footer

Can I Automatically Serialize A Dart Object To Send Over A Web Socket?

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 i

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

classPerson {
  String name;
  int age;

  Person(this.name, this.age);

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

  MaptoJson() {
    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 packagevaraddress=newAddress();
 address.street = 'N 34th';
 address.city = 'Seattle';
 varserialization=newSerialization()
     ..addRuleFor(address);
 Mapoutput= serialization.write(address);

and

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

Solution 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';

classProductextendsObjectwithExportable
{
  @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}

Post a Comment for "Can I Automatically Serialize A Dart Object To Send Over A Web Socket?"