Michael Snytko
Michael Snytko

Reputation: 337

Deserialize unknown object with protobuf-net knowing the schema

I have to parse back message of unknown type, serialized by protobuf-net.

I have succesfully parsed back FileDescriptorSet from raw bytes, I mean I know type name, it's fields etc. But how to deserialize message back withouth knowing it's type? This question and Marc's answer is close, but I fail to understand how to use Extensible class.

You might need to create a non-abstract class to play with, but class Foo : Extensible {} should suffice, then Serializer.Deserialize(source).

So I dont have "Foo", I have only FileDescriptorSet and serialized bytes of message. I need to do it in code "on-the-fly". How to marry FileDescriptorSet with byte array, containing values of unknown message type?

Upvotes: 1

Views: 704

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063013

There is no simple answer to this question, and I haven't yet had need to fully implement an example. The only thing Extensible does for us here is allow basic access to ad-hoc fields still stored as bytes. So: you can deserialize an Extensible from your data source, and then use Extensible.GetValue<Type>(obj, fieldNumber) and the associated overloads of that API. You would need to do this based on your own interpretation of the DescriptorProto that you're looking at (a DescriptorProto is a type inside a FileDescriptorSet). For example, you might enumerate .Fields, and for each: infer some <T> from the .type and .TypeName (which you would have to resolve to another DescriptorProto or EnumDescriptorProto etc), and the .Number (for the tag). For any message type, you can just use Extensible again and repeat the process recursively. You'd also need to check the .Label to see if it is repeated, and if so: use Extensible.GetValues<T> instead.

That's the theory. I haven't had the need to put it into practice.

Upvotes: 1

Related Questions