无法解组json到protobuf结构字段 [英] Unable to unmarshal json to protobuf struct field

查看:134
本文介绍了无法解组json到protobuf结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此相似的原始文件.

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

我正在尝试使用"encoding/json"库将json下面的内容解编为protobuf:

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

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

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

The code to decode request json to protobuf is:

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

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

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

推荐答案

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

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

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

这篇关于无法解组json到protobuf结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆