protobuf文本格式解析映射
问题描述:
This答案清楚地显示了一些proto文本解析的示例,但没有地图示例。protobuf文本格式解析映射
如果原有:
map<int32, string> aToB
我猜是这样的:
aToB {
123: "foo"
}
,但它不工作。有谁知道确切的语法?
答
我最初试图从earlier answer,这使我误入歧途外推,因为我错误地以为多ķ/ 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"
}
重复的名称的图案在重读this relevant portion of the proto3 Map documentation后,地图变量更有意义,这说明地图等同于定义自己的“对”消息类型,然后将其标记为“重复”。
一个更完整的示例:
原定义:
user_collection {
description = "my default users"
users {
key: "user_1234"
value {
handle: "winniepoo"
paid_membership: true
}
}
users {
key: "user_9b27"
value {
handle: "smokeybear"
}
}
}
C++,以便:在配置文件
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”)以编程方式生成消息内容
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));
答
文本格式是:
aToB {
key: 123
value: "foo"
}
尝试编码为文本格式,以便看到它应该如何? – jpa