parsing - protobuf 文本格式解析映射

标签 parsing protocol-buffers

This答案清楚地显示了一些原始文本解析的示例,但没有 map 示例。

如果一个原型(prototype)有:

map<int32, string> aToB

我猜是这样的:
aToB {
    123: "foo"
}

但它不起作用。有谁知道确切的语法?

最佳答案

我最初尝试从 earlier answer 推断,这让我误入歧途,因为我错误地认为多个 k/v 对看起来像这样:

aToB {         # (this example has a bug)
    key: 123
    value: "foo"
    key: 876        # WRONG!
    value: "bar"    # NOPE!
}

这导致了以下错误:
 libprotobuf ERROR: Non-repeated field "key" is specified multiple times.

多个键值对的正确语法:

(注意:我使用的是 Protocol Buffer 语言的“proto3”版本)
aToB {
    key: 123
    value: "foo"
}
aToB {
    key: 876        
    value: "bar"    
}

重读 this relevant portion of the proto3 Map documentation 后,重复映射变量名称的模式更有意义,这说明映射相当于定义自己的“对”消息类型,然后将其标记为“重复”。

更完整的例子:

原型(prototype)定义:
syntax = "proto3";
package myproject.testing;

message UserRecord {
  string handle = 10;
  bool paid_membership = 20;
}

message UserCollection {
  string description = 20;
  // HERE IS THE PROTOBUF MAP-TYPE FIELD:
  map<string, UserRecord> users = 10;
}

message TestData {
  UserCollection user_collection = 10;
}

配置文件中的文本格式(“pbtxt”):
user_collection {
  description = "my default users"
  users {
    key: "user_1234"
    value {
      handle: "winniepoo"
      paid_membership: true
    }
  }
  users {
    key: "user_9b27"
    value {
      handle: "smokeybear"
    }
  }
}

将以编程方式生成消息内容的 C++
myproject::testing::UserRecord user_1;
user_1.set_handle("winniepoo");
user_1.set_paid_membership(true);
myproject::testing::UserRecord user_2;
user_2.set_handle("smokeybear");
user_2.set_paid_membership(false);

using pair_type =
    google::protobuf::MapPair<std::string, myproject::testing::UserRecord>;

myproject::testing::TestData data;
data.mutable_user_collection()->mutable_users()->insert(
    pair_type(std::string("user_1234"), user_1));
data.mutable_user_collection()->mutable_users()->insert(
    pair_type(std::string("user_9b27"), user_2));

关于parsing - protobuf 文本格式解析映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902463/

相关文章:

c# - 如何解析 C# 类的方法体内的所有公共(public)方法名称和方法调用?

Javascript 获取两个日期之间的时差

c# - 如何在AspNet Core gRPC Service中导入protobuf知名类型

json - Flutter - 如何将嵌套的 json 解析为具有泛型的类?

java - REST API 使用动态 JSON

java - 为什么在解析 XML 时得到空节点值

c++ - ProtocolBuffer 无法定义数据,尽管它已被接收

java - 如何从 Java 的标准输入读取 python 二进制字符串

java - Google protobuf可以用于android中C和Java服务之间的通信吗?

c - 协议(protocol)消息反序列化不当