我如何知道 protobuff 的 json 格式应该是什么样的?

我是 protobuf 的新手,我想将一些 protobuf 保存为 json 格式,并知道 protobuf 的完整格式是什么。我尝试创建一个空的 protobuf 实例,并将其保存为 json,但这只给了我一个空的 json 对象,{}.

如果我填写一个属性的值,并序列化它,我会在 json 中得到该属性,这很好,但我不想对每个 protobuf 的所有属性都执行此操作,我想这样做。

有没有办法让我查看 protobuf 的完整 json 格式,而无需为每个字段提供值?

笔记

  • 我在 Java 中使用 Google 的 protobuf 库,并且可以序列化和反序列化我的对象,我只是不确定如何为特定对象编写 json。

  • 我已经查看了这个 stackoverflow 问题以获取信息,但没有发现任何帮助。


一只甜甜圈
浏览 55回答 2
2回答

隔江千里

是的,proto3 的 JSON 格式已记录。或者,要查看示例而不更改默认值,您可以includingDefaultValueFields在打印时指定:String json = JsonFormat.printer().includingDefaultValueFields().print(message);(这至少应该适用于基元;我怀疑null如果嵌套消息尚未初始化,它会打印嵌套消息。)

阿晨1998

是我为了我的目的而总结的 - 你的结果可能会有所不同,哈哈!这允许我从 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;  }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java