Reputation: 7712
I want to send/receive values with arbitrary types. At first, I thought the Any
type would allow types such as string
int32
etc. but it seems that the type must implement IMessage
to pack or unpack it.
Is there a way to convert a string
to an Any
and vice versa?
If not, is there some other way to allow arbitrary types in messages?
E.g.
syntax = "proto3";
import "google/protobuf/any.proto";
package Engine;
message SomeMessage {
string Id = 1;
google.protobuf.Any AttributeValue = 2;
}
This code gives a compilation error in C#.
var someMessage = new SomeMessage
{
Id = "123",
AttributeValue = Any.Pack("Test")
};
Argument 1: cannot convert from 'string' to 'Google.Protobuf.IMessage'
Upvotes: 5
Views: 1398
Reputation: 75
Packing a string in an Any type:
var someMessage = new SomeMessage
{
Id = "123",
AttributeValue = Any.Pack(new StringValue { Value = "foo bar"})
};
Unpacking the string:
var data = pack.Unpack<StringValue>();
doSomething(data.Value);
Upvotes: 1
Reputation: 7712
It looks as though the answer may be the Value
type.
syntax = "proto3";
import "google/protobuf/struct.proto";
package Engine;
message SomeMessage {
string Id = 1;
google.protobuf.Value AttributeValue = 2;
}
Upvotes: 4