【问题标题】:How do I know what the json for a protobuff should be formatted like?我怎么知道 protobuf 的 json 格式应该是什么样的?
【发布时间】:2020-02-23 16:01:08
【问题描述】:

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

如果我为一个属性填写一个值并对其进行序列化,我会在 json 中获得该属性,这很好,但我不想对我想要的每个 protobuf 的所有属性都这样做这样做。

有没有办法让我在不为每个字段提供值的情况下查看 protobuf 的完整 json 格式?

笔记
  • 我在 Java 中使用 Google 的 protobuf 库,并且可以序列化和反序列化我的对象,我只是不确定如何为特定对象编写 json。
  • 我查看了 this stackoverflow question 的信息,但没有发现任何帮助。

【问题讨论】:

    标签: java protocol-buffers protobuf-c


    【解决方案1】:

    是的,JSON formatting for proto3 is documented

    或者,要查看示例而不更改默认值,您可以在打印时指定includingDefaultValueFields

    String json = JsonFormat.printer().includingDefaultValueFields().print(message);
    

    (这至少应该适用于原语;我怀疑如果嵌套消息尚未初始化,它会为嵌套消息打印null。)

    【讨论】:

    • 它似乎只适用于原语,但总比没有好......谢谢!如果你设置一个对象,它会转储它并且它是原语,非常有帮助。
    • 如果其他人想知道如何为任何嵌套消息创建实例,每个对象上都有一个 .newBuilder() 方法可以让您创建实例
    【解决方案2】:

    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;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多