如何转换Json至Protobuf?

时间:2022-10-29 23:44:43

I'm new to using protobuf, and was wondering if there is a simple way to convert a json stream/string to a protobuf stream/string in Java?

我是新手使用protobuf,并想知道是否有一种简单的方法将json流/字符串转换为Java中的protobuf流/字符串?

For example,

例如,

protoString = convertToProto(jsonString)

I have a json string that I want to parse into a protobuf message. So, I want to first convert the json string to protobuf, and then call Message.parseFrom() on it.

我有一个json字符串,我想解析为protobuf消息。所以,我想首先将json字符串转换为protobuf,然后在其上调用Message.parseFrom()。

Thanks in advance for the help!

先谢谢您的帮助!

1 个解决方案

#1


11  

With proto3 you can do this using JsonFormat. It parses directly from the JSON representation, so there is no need for separately calling MyMessage.parseFrom(...). Something like this should work:

使用proto3,您可以使用JsonFormat执行此操作。它直接从JSON表示解析,因此不需要单独调用MyMessage.parseFrom(...)。像这样的东西应该工作:

JsonFormat.parser().merge(json_string, builder);

#1


11  

With proto3 you can do this using JsonFormat. It parses directly from the JSON representation, so there is no need for separately calling MyMessage.parseFrom(...). Something like this should work:

使用proto3,您可以使用JsonFormat执行此操作。它直接从JSON表示解析,因此不需要单独调用MyMessage.parseFrom(...)。像这样的东西应该工作:

JsonFormat.parser().merge(json_string, builder);