protobuf 枚举值对应到字符串的转换

在protobuf的开发中,经常遇到pb转到json,然后又需要从json转为对应的pb,enum值需要有一个反射来做到值和字符串的映射,官方提供了对应的反射接口:

链接: EnumValueDescriptor
链接: EnumDescriptor

  • To get a EnumDescriptor
To get the EnumDescriptor for a generated enum type, call TypeName_descriptor(). Use DescriptorPool to construct your own descriptors.
  • To get the string value, use FindValueByNumber(int number)
const EnumValueDescriptor * EnumDescriptor::FindValueByNumber(int number) const

Looks up a value by number.

Returns NULL if no such value exists. If multiple values have this >number,the first one defined is returned.

example:

enum UserStatus {
  AWAY = 0;
  ONLINE = 1;
  OFFLINE = 2;
}


const google::protobuf::EnumDescriptor *descriptor = UserStatus_descriptor();
std::string name = descriptor->FindValueByNumber(UserStatus::ONLINE)->name();
int number = descriptor->FindValueByName("ONLINE")->number();

std::cout << "Enum name: " << name << std::endl;
std::cout << "Enum number: " << number << std::endl;

你可能感兴趣的:(protobuf)