如何将 JSON 数组建模为 protobuf 定义

zaR*_*Roc 6 arrays json go protocol-buffers grpc

我正在使用 protobuf 在 golang 中编写一项新服务。我想在 .proto 文件中对以下请求 JSON 进行建模。

[
   {
    "var": ["myVariable1","myVariable2"], 
    "key1": 123123,
    "key2": 1122,
    "key3": "abcd-0101"
   },
  { 
    "var": ["myVariable1"], 
    "key1": 123124,
    "key2": 1123,
    "key3": "abcd-0102"
  },
] 
Run Code Online (Sandbox Code Playgroud)

目前存在两个问题:

  • 每个数组元素中的键事先未知,因此我无法在 .proto 文件中创建消息并使其重复。我需要保留它的地图
  • 我无法对 json 进行建模,它只是一个没有键的数组。每次我这样做时,都会显示以下错误:无法解码请求:json:无法将数组解组为Go值

以下是我的 .proto 文件:

syntax = "proto3";

package pb;

import "google/protobuf/empty.proto";
import "google/api/annotations.proto";

service Transmitter {
  rpc GetVariables(GetVariablesRequest) returns (GetVariablesResponse) {
    option (google.api.http) = {
                post: "/api/v1/{Service}/getVars"
                body: "*"
            };
  };
}


message GetVariablesRequest {
  string Service = 1;
  repeated GetVarInput in = 2;
}

message GetVariablesResponse {
  string msg = 1;
}

message GetVarInput {
  map<string,string> Input = 2;
}
Run Code Online (Sandbox Code Playgroud)

我尝试过使用字节而不是重复的 GetVarInput,但它总是为空。还尝试了 body: "*" 和 body: "in"

请提供一些指示。

小智 3

您可以为 json 编写一条消息,如下所示:

message RequestMessage {
   string var = 0;
   double key1 = 1;
   double key2 = 2;
   string key3 = 3;
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以创建另一条消息,其中包含一组RequestMessage

message Request {
   repeated RequestMessage request = 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为请求将映射到 json 对象而不是数组。它将是 {"request":[]}。如何直接映射到数组? (8认同)