使用nlohmann庫實現protobuf數據轉爲Json數據

使用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"]}      //運行結果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章