如何转换Json至Protobuf? [英] How to convert from Json to Protobuf?
问题描述
我刚开始使用protobuf,并且想知道是否有一种简单的方法可以将json流/字符串转换为Java中的protobuf流/字符串?
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?
例如,
protoString = convertToProto(jsonString)
我有一个json字符串,我想解析为protobuf消息。所以,我想首先将json字符串转换为protobuf,然后在其上调用 Message.parseFrom()
。
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.
提前感谢您的帮助!
推荐答案
使用proto3,您可以使用 JsonFormat 。它直接从JSON表示解析,因此不需要单独调用 MyMessage.parseFrom(...)
。这样的事情应该有效:
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:
JsonFormat.parser().merge(json_string, builder);
这篇关于如何转换Json至Protobuf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!