使用nlohmann库实现protobuf数据转为Json数据。核心代码如下,代码细节咨询可以留言:
Json pb2json(const Message *msg) //pb数据转json
{
Json json=parse_msg(msg); //解析pb数据
return json; //返回json对象
}
Json parse_msg(const Message *msg) //解析pb数据
{
cosnt Descriptor *d=msg->GetDescriptor();//获取message(pb)数据的描述
size_t count =d->field_count(); //获取message中字段的数量
Json root;
for(size_t i=0;i<count;++i)
{
const FieldDescriptor *field = d->field(i);//使用FieldDescriptor来获取字段的描述
Json field_json = field2json(msg,field); //将字段信息转化为json数据
root[field->name()]=field_json; //插入数据,返回Json对象
}
return root;
}
Json field2json(const Message *msg,const FieldDescriptor *field)
{
const Reflection *ref = msg->GetReflection(); //定义Reflection,获取message的属性和方法
const bool repeated = field->is_repeated(); //判断field是否用repeated修饰
size_t array_size=0;
if(repeated)
{
array_size=ref->FieldSize(*msg,field); //获取字段中元素的数量
}
Json json;
swich(filed->cpp_type()) //获取字段数据类型
{
case fieldDescriptor::CPPTYPE_STRING: //当数据类型为string
if(repeated)
{
for(size_t i=0;i!=array_size;++i)
{
std::string value=ref->GetRepeatedString(*msg,field,i);//获取字段的值
json.push_back(value); //添加数据
}
}
else
{
json.push_back(ref->GetString(*msg,field));
}
break;
//其他类型如int32,int64,bool,enum,message类型实现类似
default:
break;
}
return json;
}
protobuf文件:
syntax ="proto3";
package test_ref;
message PersonData
{
string english_name=1;
}
测试代码:
test_ref::PersonData stringData;
stringData.set_english_name("kxc");
Json strData=pb2json(&stringData);
std::cout<<"string类型测试"<<strData.dump()<<std::endl;
运行结果:
string类型测试:{"english_name":["kxc"]} //运行结果