douli4337 2017-10-26 03:48
浏览 602

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

I am writing a new service in golang using protobuf. I want to model the following Request JSON in the .proto file.

[
   {
    "var": ["myVariable1","myVariable2"], 
    "key1": 123123,
    "key2": 1122,
    "key3": "abcd-0101"
   },
  { 
    "var": ["myVariable1"], 
    "key1": 123124,
    "key2": 1123,
    "key3": "abcd-0102"
  },
] 

There are two problems currently :

  • The keys in each array element are not known beforehand, hence I cannot create a message in .proto file and make it repeated. I need to keep it map
  • I am unable to model a json which is just an array with no key. Everytime i do this, following error is shown : failed to decode request: json: cannot unmarshal array into Go value

Following is my .proto file :

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

I have tried with bytes instead of repeated GetVarInput, but it always comes empty. Also tried body: "*" and body : "in"

Please provide some pointers.

  • 写回答

3条回答 默认 最新

  • dongzhong9055 2017-10-27 05:50
    关注

    The answer by Satyam Zode seems like the most reasonable one.

    In your original question, you are trying to keep all the flexibility and dynamic nature of JSON, and in that case trying to convert it into protobuf makes little sense. You could just have a string field that contains the json.

    However, protobuf does handle future changes to RequestMessage contents quite well, so you do not have to know the final set of fields yet. Just follow Updating a Message Type to keep them compatible between different .proto file versions.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度