简体   繁体   English

在C#中反序列化protobuf

[英]Deserializing protobuf in c#

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? 我最近开始在我的项目中使用protobuf,我想知道,如果我不确切知道我拥有什么实体,是否可以通过某种方式反序列化protobuf? When I am working with JSON or XML I can easily do it. 当我使用JSON或XML时,我可以轻松做到。

I was searching for some way to convert protobuf to json or xml, but found nothing for c#. 我正在寻找将protobuf转换为json或xml的方法,但没有为c#找到任何东西。

I have already looked in popular libraries, but they can only serialize json to protobuf, but not in both directions. 我已经看过流行的库,但是它们只能将json序列化为protobuf,而不能双向进行。 Does someone know how to solve this problem? 有人知道如何解决这个问题吗? I would be appreciative for any advice or solution! 对于任何建议或解决方案,我将不胜感激!

In general, you can't work with protobufs if you don't know the message format. 通常,如果您不知道消息格式,则不能使用protobuf。 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. JSON和XML在消息中包含许多额外的内容,即使您不知道它们包含的内容,也可以使您(有点)使用它们,但是要权衡取舍是一种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 如果要在单个消息中包装几种不同的消息类型,请查看联合类型: 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 有一种使用自我描述消息的解决方法(在注释中提到),但是我从未发现它们有用,而且谷歌显然也没有: https : //developers.google.com/protocol-buffers/docs /技术#自我描述

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

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