protobuf文本格式解析地图

时间:2016-12-01 04:05:49

标签: parsing protocol-buffers

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

如果原型有:

map<int32, string> aToB

我猜想会像:

aToB {
    123: "foo"
}

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

2 个答案:

答案 0 :(得分:4)

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

多个键值对的正确语法:

(注意:我正在使用&#34; proto3&#34;协议缓冲区语言版本)

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

在重新阅读this relevant portion of the proto3 Map documentation之后,重复地图变量名称的模式更有意义,这解释了地图相当于定义自己的&#34;对&#34;消息类型,然后将其标记为&#34;重复&#34;。

更完整的示例:

原型定义:

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;
}
配置文件中的

文本格式(&#34; pbtxt&#34;):

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

答案 1 :(得分:1)

文本格式为:

aToB {
    key: 123
    value: "foo"
}