当前位置: > > > > Marshal/Unmarshal google.protobuf.Any proto 消息
Marshal/Unmarshal google.protobuf.Any proto 消息
来源:stackoverflow
2024-04-29 08:03:36
0浏览
收藏
偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《Marshal/Unmarshal google.protobuf.Any proto 消息》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!
问题内容
我目前正在使用 grpc 进行 api 通信。现在我需要我的请求的值可以接受任何数据类型,无论是 struct object 还是只是一个原始数据类型,如单个 integer、string 或 bolean。我尝试使用 google.protobuf.any 如下,但当我想要编组和解组它时它不起作用。
message myrequest {
google.protobuf.any item = 1; // could be 9, "a string", true, false, {"key": value}, etc.
}
原始编译结果:
type myrequest struct {
item *anypb.any `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"`
}
我将通过 grpc 编组传入请求并将其作为 json 字符串保存在数据库中:
bytes, err = json.marshal(m.request.item)
if err != nil {
return err
}
itemstr := string(bytes)
但是当我想通过以下方式将字符串解组回 *anypb.any 时:
func getItem(itemStr string) (structpb.Value, error) {
var item structpb.Value
err := json.Unmarshal([]byte(itemStr), &item)
if err != nil {
return item, err
}
// also I've no idea on how to convert `structpb.Value` to `anypb.Any`
return item, nil
}
它返回一个错误,这似乎是因为 struct *anypb.any 不包含我编码的 item 字符串中的任何字段。有没有正确的方法来解决这个问题?
正确答案
考虑使用
在文档中,它展示了如何解组它的示例
m := new(foopb.MyMessage)
if err := any.UnmarshalTo(m); err != nil {
... // handle error
}
... // make use of m
以上就是《Marshal/Unmarshal google.protobuf.Any proto 消息》的详细内容,更多关于的资料请关注米云公众号!
