【问题标题】:Unable to unmarshal json to protobuf struct field无法将 json 解组为 protobuf 结构字段
【发布时间】:2019-03-28 01:23:18
【问题描述】:

我有一个类似的 proto 文件。

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\""];
}

我正在尝试使用“encoding/json”库将下面的 json 解组为 protobuf:

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

将请求json解码为protobuf的代码是:

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

但 JobCreateRequest 结构中的结果数据字段始终设置为 nil。在protobuf中使用struct Value的正确方法是什么?

【问题讨论】:

    标签: json go protocol-buffers


    【解决方案1】:

    如果你使用google.golang.org/protobuf,那么你可以使用google.golang.org/protobuf/encoding/protojson进行转换。

    req := &proto.JobCreateRequest{}
    err := protojson.Unmarshal(bytes, req)
    

    【讨论】:

      【解决方案2】:

      您可以使用github.com/golang/protobuf/jsonpb 将 JSON 转换为 protobuf。

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

      【讨论】:

      猜你喜欢
      • 2020-12-27
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 2021-07-05
      相关资源
      最近更新 更多