问题描述
我刚刚看到有一些运行Dart网络服务器的库,如。
所以我在想像这样..
如果客户端和服务器代码都是在Dart中编写的,是否可以通过websockets(或正常的REST)发送Dart对象,以便类型信息保留在另一端?或者我需要通过JSON或类似的方式序列化/反序列化?
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?
关于Oskar
推荐答案
你需要以某种方式序列化Dart对象。您可以尝试使用JSON,也可以尝试使用重型。
You will need to serialize the Dart object somehow. You can try JSON, or you can try the heavy-duty serialization package.
没有针对自定义Dart类的完全自动JSON序列化。您需要添加自定义的toJson序列化程序,并创建一些fromJson构造函数。
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.
例如。如果你有一个Person类,你可以这样做:
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};
}
}
注意: fromJson
只是一个约定。你需要以某种方式调用它,没有内置的机制来接受一个任意的JSON字符串,并在你的自定义对象上调用正确的构造函数。
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);
和
// uses serialization
var serialization = new Serialization()
..addRuleFor(address,
constructor: "create",
constructorFields: ["number", "street"],
fields: ["city"]);
这篇关于我可以自动序列化一个Dart对象通过Web Socket发送吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!