2

I have recently started working with protobuf in my project and I am wondering, is there some way to deserialize a proto message if I don't know exactly what entity I have? When I am working with JSON or XML I can easily do it.

I was searching for some way to convert protobuf to json or xml, but found nothing for c#.

I have already looked in popular libraries, but they can only serialize json to protobuf, but not in both directions. Does someone know how to solve this problem? I would be appreciative for any advice or solution!

engineerC
  • 2,808
  • 17
  • 31
RenDishen
  • 928
  • 1
  • 10
  • 30
  • Your protobuf needs to be self describing. See http://stackoverflow.com/questions/3018743/whats-the-right-way-to-do-polymorphism-with-protocol-buffers for solutions. – Remus Rusanu Jul 09 '15 at 08:55

1 Answers1

3

In general, you can't work with protobufs if you don't know the message format. In order to be compact the wire format doesn't include all the information necessary to reconstruct the message. JSON and XML contain a lot of extra stuff in the message that allows you to (kind of) work with them even if you have no idea what they contain, but the trade-off there is a bloated format.

By the way, do not try to "guess" what a message is by going down a list of possible message formats and trying one after the other until your message successfully deserializes. It's entirely possible to "get lucky" and have a message of one type successfully deserialize as a different type, but with bogus data. I have been bitten by that one rather badly. :(

Look at union types if you want to wrap several different message types in a single message: https://developers.google.com/protocol-buffers/docs/techniques#union

There is a workaround (mentioned in the comments) of using self-describing messages, but I've never found them to be useful and evidently google didn't either: https://developers.google.com/protocol-buffers/docs/techniques#self-description

engineerC
  • 2,808
  • 17
  • 31