定义一组预先填充的protobuf消息



我希望能够按名称提供预先实例化的消息,而不是从头开始填充。例如,给定以下模式:

message Animal {
required int32 num_legs = 1;
required int32 num_eyes = 2;
}
message Zoo {
repeated Animal animals;
}

我想通过从一组已知动物中进行选择,能够在我的配置文件中快速定义动物园:

// config.json
zoo: {
animals: [snake, bird]
}

蛇和鸟已经被定义:

// animals.json
bird: {
num_legs: 2
num_eyes: 2
}
snake: {
num_legs: 0
num_eyes: 2
}

做这件事最优雅的方法是什么?

protobuf API具有转换protobuf的方法⬌JSON。对于C++,您可以使用util::JsonStringToMessage,其他语言也有其API版本(您没有指定语言(。将其封装在一个简单的helper函数中,并使用语言的多行字符串常量语法将JSON格式的消息直接嵌入到源代码中。

要获取已命名的预定义消息,请使用具有字符串插值功能的语言。(不幸的是,这不是C++的原生版本,但这里有一个SO的答案,讨论了如何做到这一点。(

最新更新