【问题标题】:protobuf text format parsing mapsprotobuf 文本格式解析映射
【发布时间】:2016-12-01 04:05:49
【问题描述】:

This的回答清楚地展示了一些原型文本解析的例子,但没有地图的例子。

如果一个原型有:

map<int32, string> aToB

我猜是这样的:

aToB {
    123: "foo"
}

但它不起作用。有谁知道具体的语法吗?

【问题讨论】:

  • 尝试编码成文本格式,看看效果如何?

标签: parsing protocol-buffers


【解决方案1】:

我最初尝试从 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.

多个键值对的正确语法:

(注意:我使用的是“proto3”版本的协议缓冲区语言)

aToB {
    key: 123
    value: "foo"
}
aToB {
    key: 876        
    value: "bar"    
}

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


一个更完整的例子:

原型定义:

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

【讨论】:

  • 顺便说一句,您还可以像这样对地图字段进行分组:field_name: [{key: 1, value: 2}, {key: 3, value: 4}, ...]
【解决方案2】:

文本格式为:

aToB {
    key: 123
    value: "foo"
}

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多