Java 如何从 Json 转换为 Protobuf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38406211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert from Json to Protobuf?
提问by Karan Tibrewal
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!
在此先感谢您的帮助!
回答by Adam Cozzette
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);
回答by Ayyub Kolsawala
//You can use this for converting your input json to a Struct / any other Protobuf Class
import com.google.protobuf.Struct.Builder;
import com.google.protobuf.Struct;
import com.google.protobuf.util.JsonFormat;
import org.json.JSONObject;
JSONObject parameters = new JSONObject();
Builder structBuilder = Struct.newBuilder();
JsonFormat.parser().merge(parameters.toString(), structBuilder);
// Now use the structBuilder to pass below (I used it for Dialog Flow V2 Context Management)