我是protobuf的新手,我想将一些protobuf的格式保存为json格式,并知道protobuf的完整格式是什么。我尝试只创建一个protobuf的空实例,并将其保存到json,但这只给了我一个空的json对象{}
。
如果我为属性填写一个值并进行序列化,则会在json中获取该属性,这很棒,但是我不想对我想要的每个protobuf的所有属性都执行此操作为此。
我是否可以在不为每个字段提供值的情况下查看protobuf的完整json格式?
笔记答案 0 :(得分:1)
是的,JSON formatting for proto3 is documented。
或者,要查看不更改默认设置的示例,可以在打印时指定includingDefaultValueFields
:
String json = JsonFormat.printer().includingDefaultValueFields().print(message);
(这至少应适用于基元;如果它们未初始化,我怀疑它将为嵌套消息打印null
。)
答案 1 :(得分:0)
与 in this answer to this question 所做的没有什么不同,但这是我出于我的目的进行的包装 - 您的结果可能会有所不同,哈哈!这允许我从 json 文件加载消息,并反序列化为对 grpc 方法的请求。
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
/**
* Convert gRPC message to Json string.
*
* @param messageOrBuilder the gRPC message
* @return a Json string
*/
public static String grpcMessageToJson(MessageOrBuilder messageOrBuilder) {
String result = "";
if (messageOrBuilder == null) {
return result;
}
try {
result = JsonFormat.printer().print(messageOrBuilder);
} catch (InvalidProtocolBufferException e) {
LOGGER.warn("Cannot serialize the gRPC message.", e);
}
return result;
}