Unable to unmarshal json to protobuf struct field

末鹿安然 提交于 2020-01-24 14:21:30

问题


I have a proto file similar to this.

syntax = "proto3";
package proto;
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/protobuf/struct.proto";


message JobCreateRequest {
    string Name = 1 [(gogoproto.jsontag) = "name", (gogoproto.moretags)= "validate:\"required,max=100\""];
    string Description = 2 [(gogoproto.jsontag) = "description", (gogoproto.moretags) = "validate:\"required,max=100\""];
    google.protobuf.Value Data = 3 [(gogoproto.jsontag) = "data", (gogoproto.moretags) = "validate:\"required\""];
}

I am trying to unmarshal below json into protobuf using "encoding/json" library:

{
 "name": "India",
 "description": "test job",
 "data": { 
    "id": 1 
  }
}

The code to decode request json to protobuf is:

json.NewDecoder(r.Body).Decode(req)

But the resulting Data field inside JobCreateRequest struct is always set to nil. What is the right way to use struct Value in protobuf?


回答1:


You can use github.com/golang/protobuf/jsonpb to convert JSON to protobuf.

req := proto.JobCreateRequest{}
jsonpb.Unmarshal(r.Body, &req)


来源:https://stackoverflow.com/questions/52955253/unable-to-unmarshal-json-to-protobuf-struct-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!