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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ronan_ka/article/details/82864415

在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;
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页