Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use protobuf's Any in C#?

Here is my protobuf's data model:

message GetNewsRespone{
  repeated google.protobuf.Any instrument = 1;
}

message Issue{
  int64 id = 1;
  string title = 2;
}

And here is my attempt to fill that with data:

GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
layer.instrument .AddRange(???);

How can I add anIssue to my GetNewsRespone.instrument, which is an Any Array?

like image 214
H su hsu Avatar asked Jul 09 '20 06:07

H su hsu


People also ask

What is protobuf C?

This is protobuf-c, a C implementation of the Google Protocol Buffers data serialization format. It includes libprotobuf-c , a pure C library that implements protobuf encoding and decoding, and protoc-c , a code generator that converts Protocol Buffer . proto files to C descriptor code.

What are Protobufs used for?

Protocol Buffers (Protobuf) is a free and open-source cross-platform data format used to serialize structured data. It is useful in developing programs to communicate with each other over a network or for storing data.

How do I read a proto file?

generate the necessary stubs in your chosen platform from the schema (https://protogen.marcgravell.com/ may be useful here) then: use the protbuf library's "deserialize" API for your chosen platform to load the data into an object model. finally: inspect the object model, now populated with the data.

How do I use Google protobuf?

To use the Any type, you must import the google/protobuf/any. proto definition. In the C# code, the Any class provides methods for setting the field, extracting the message, and checking the type. Protobuf's internal reflection code uses the Descriptor static field on each generated type to resolve Any field types.


1 Answers

Use Google.Protobuf.WellKnownTypes.Any.Pack

like:

var myValue = Google.Protobuf.WellKnownTypes.Any.Pack(new Stock());

for your code:

GetNewsRespone res = new GetNewsRespone();
Issue issue = new Issue();
issue.id = 123;
res.instrument = Google.Protobuf.WellKnownTypes.Any.Pack(issue);
like image 152
Toine db Avatar answered Oct 17 '22 07:10

Toine db