简体   繁体   English

Marshal/Unmarshal google.protobuf.Any proto 消息

[英]Marshal/Unmarshal google.protobuf.Any proto message

I'm currently using gRPC for my API communication.我目前正在使用 gRPC 进行 API 通信。 Now I need the value of my request can accept any data type, be it a struct object or just a primitive data type like single integer , string , or boolean .现在我需要我的请求的值可以接受任何数据类型,无论是struct object还是像单个integerstringboolean这样的原始数据类型。 I tried using google.protobuf.Any as below but it doesn't work when I want to marshal and unmarshal it.我尝试使用google.protobuf.Any如下,但是当我想编组和解组它时它不起作用。

message MyRequest {
    google.protobuf.Any item = 1; // could be 9, "a string", true, false, {"key": value}, etc.
}

proto-compiled result:原型编译结果:

type MyRequest struct {
    Item *anypb.Any `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"`
}

I will marshal the incoming request through gRPC and save it as a JSON string in the database:我将通过 gRPC 编组传入的请求,并将其保存为数据库中的 JSON 字符串:

bytes, err = json.Marshal(m.request.Item)
if err != nil {
    return err
}
itemStr := string(bytes)

But when I want to unmarshal the string back into *anypb.Any by:但是当我想通过以下方式将字符串解组回*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
}

It returns an error which seems to be because the struct *anypb.Any doesn't contain any of the fields in my encoded item string.它返回一个错误,这似乎是因为 struct *anypb.Any不包含我的编码item字符串中的任何字段。 Is there a correct way to solve this problem?有没有解决这个问题的正确方法?

Consider usinganypb考虑使用anypb

In the documentation it shows an example of how to unmarshal it在文档中,它显示了如何解组它的示例

m := new(foopb.MyMessage)
if err := any.UnmarshalTo(m); err != nil {
    ... // handle error
}
... // make use of m

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM