Ara*_*vin 4 protocol-buffers grpc proto3 protobuf.js grpc-node
如何在 ProtoBuf - Proto3 语法中将消息类型作为对象发送?
我想传输对象而不是字符串或数字。
{
name: 'One',
date: 'date',
some: 'some',
...
...
}
Run Code Online (Sandbox Code Playgroud)
syntax = "proto3";
package db;
service Proxy
{
rpc myFunction(Request) returns (Response);
}
message Request
{
string name = 1;
}
message Response
{
object keyvalue = 1;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我收到错误
throw Error("no such Type or Enum '" + path + "' in " + this);
^
Error: no such Type or Enum 'object' in Type
Run Code Online (Sandbox Code Playgroud)
——
我可以在服务器端将它转换为字符串,然后我可以在客户端 JSON.parse() 。
但我想知道,是否有更好的方法来做到这一点。
协议缓冲区不支持对象数据类型!
但是您可以通过使用协议缓冲区消息类型本身来分层模拟数据。
syntax = "proto3";
package db;
service Proxy
{
rpc myFunction(Request) returns (Response);
}
message Request
{
string name = 1;
}
message Response
{
message obj {
string key1 = 1;
string key2 = 2
}
obj keyvalue = 1; // Here you have created your own type obj.
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,您可以看到 Response 消息现在具有obj类型的“ keyvalue ”字段(这是您刚刚构建的自定义类型)。
现在您将在来自服务器的回调中传递 Object 而不是原始类型。
callback(null, { keyvalue: { key1: "value1", key2: "value2" } });
Run Code Online (Sandbox Code Playgroud)
假设您不知道键,但键/值对数据类型相同并且您知道,在这种情况下,您可以使用
map<type, type>
message Response
{
map<string, string> keyvalue = 1;
}
callback(null, { keyvalue: { "key1": "value1", "key5": "value2" } });
Run Code Online (Sandbox Code Playgroud)
参考:-
小智 2
根据您想要完成的任务,您可以使用三种类型之一。
bytes类型表示任意字节字符串。您可以选择以您认为合适的方式对类型进行编码。 any类型表示任意 protobuf 消息,允许客户端或服务器对非预定义消息进行编码。这是一串字节,每个消息类型都有唯一的标识符,并且语言实现将有方法解包消息。oneof您可以使用基本类型和map对象类型的组合来定义 Javascript 对象消息。| 归档时间: |
|
| 查看次数: |
4553 次 |
| 最近记录: |