0

I want to be able to supply a pre-instantiated message by name rather than populating it from scratch. For example, given the following schema:

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

message Zoo {
  repeated Animal animals;
}

I want to be able quickly to define a Zoo in my config file by choosing from a set of known animals:

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

where snake and bird are already defined:

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

snake: {
  num_legs: 0
  num_eyes: 2
}

What's the most elegant way to do this?

Alex
  • 301
  • 3
  • 7

1 Answers1

1

The protobuf API has methods to convert protobuf⬌JSON. For C++ you can use util::JsonStringToMessage, other languages have their API versions too (you didn't specify a language). Wrap this in a simple helper function and use your language's multi-line string constant syntax to embed the message in JSON format directly into your source.

To get your named predefined messages, use a language that has string interpolation. (Not native to C++, unfortunately, but here is a SO answer talking about ways you might do it.)

davidbak
  • 5,775
  • 3
  • 34
  • 50