将 protobuf 映射表示为 json

Represent a protobuf map as a json

我正在使用基于 protobuf.js 的 grpcc 来测试我的 grpc 服务 API。

我的 .proto 文件:

message MyRequest {
    string userId = 1;
    map<string, string> params = 2;
}

我尝试了以下 json 正文来发送请求:

{userId : "my_user_id" , params: { name: "my_name"}}
{userId : "my_user_id" , params: [{"name":"my_name"}] }

但这会产生以下错误:

Error: Illegal value for Message.Field....MyRequest.params of type string: object (expected ProtoBuf.Map or raw object for map field)

如何将 protobuf 映射正确表示为 json?

正确的 json 正文如下:

{ "userId": "my_user_id", "params": { "name": "my_name" } }

您尝试做的是一组映射,这在 protobuf 的上下文中没有任何意义。一个 map<string, string> 恰好是一个 json 对象的描述,所以不止一个值可以用下面的方式表示:

{ "params": { "key1": "value1", "key2": "value2" } }

不需要数组。