为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只甜甜圈 2024-01-05 16:36:37
我是 protobuf 的新手,我想将一些 protobuf 保存为 json 格式,并知道 protobuf 的完整格式是什么。我尝试创建一个空的 protobuf 实例,并将其保存为 json,但这只给了我一个空的 json 对象,{}.如果我填写一个属性的值,并序列化它,我会在 json 中得到该属性,这很好,但我不想对每个 protobuf 的所有属性都执行此操作,我想这样做。有没有办法让我查看 protobuf 的完整 json 格式,而无需为每个字段提供值?笔记我在 Java 中使用 Google 的 protobuf 库,并且可以序列化和反序列化我的对象,我只是不确定如何为特定对象编写 json。我已经查看了这个 stackoverflow 问题以获取信息,但没有发现任何帮助。
查看完整描述

2 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

是的,proto3 的 JSON 格式已记录。

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

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

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


查看完整回答
反对 回复 2024-01-05
?
阿晨1998

TA贡献2037条经验 获得超6个赞

是我为了我的目的而总结的 - 你的结果可能会有所不同,哈哈!这允许我从 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;

  }


查看完整回答
反对 回复 2024-01-05
  • 2 回答
  • 0 关注
  • 48 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信