C/C++ protobuf与json互转

  1. 测试环境

    • ubuntu16.04 64bit
    • protocbuf:3.9.1 (支持json转换需>=3.0.0)
  2. 协议

    cpp 复制代码
    syntax = "proto2";
    
    message Person{
    	optional string name = 1;
    	optional uint32 age = 2;
    	optional string address = 3;
    }
  3. 测试代码

    cpp 复制代码
    //protobuf >= 3.0.0
    
    #include "person.pb.h"
    #include "google/protobuf/stubs/stringpiece.h"
    #include "google/protobuf/util/json_util.h"
    #include <iostream>
    
    bool proto_to_json(const google::protobuf::Message& message, std::string& json) {
        google::protobuf::util::JsonPrintOptions options;
        // options.add_whitespace = true;
        return MessageToJsonString(message, &json, options).ok();
    }
    
    bool json_to_proto(const std::string& json, google::protobuf::Message& message) {
        google::protobuf::util::JsonParseOptions options;
        return JsonStringToMessage(json, &message, options).ok();
    }
    
    int main(int argc, char* argv[]){
        std::string person_json;
    
        Person person;
        person.set_name("hb");
        person.set_age(20);
        person.set_address("sjz");
    
        if (!proto_to_json(person, person_json)) {
            std::cout << "pb to json failed!" << std::endl;
        }else{
            std::cout << "pb to json:" << person_json << std::endl;
        }
    
        person.Clear();
        person_json.clear();
        person_json = "{\"name\": \"HB\", \"age\": 22, \"address\": \"SJZ\" }";
        if (!json_to_proto(person_json, person)) {
            std::cout << "json to pb failed!" << std::endl;
        }else{
            std::cout << "json to pb: name:" << person.name() << " age:" << person.age() << " address:" << person.address() << std::endl;
        }
        return 0;
    }
  4. 编译

    • 编译协议

      powershell 复制代码
      protoc --cpp_out=. person.proto 
    • 编译代码

      powershell 复制代码
      g++ person.pb.cc demo.cpp -lprotobuf -lpthread -o demo && ./demo
  5. 运行结果

    powershell 复制代码
    pb to json:{"name":"hb","age":20,"address":"sjz"}
    json to pb: name:HB age:22 address:SJZ
相关推荐
Want5951 天前
C/C++跳动的爱心①
c语言·开发语言·c++
lingggggaaaa1 天前
免杀对抗——C2远控篇&C&C++&DLL注入&过内存核晶&镂空新增&白加黑链&签名程序劫持
c语言·c++·学习·安全·网络安全·免杀对抗
phdsky1 天前
【设计模式】建造者模式
c++·设计模式·建造者模式
H_-H1 天前
关于const应用与const中的c++陷阱
c++
coderxiaohan1 天前
【C++】多态
开发语言·c++
gfdhy1 天前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
我不会插花弄玉1 天前
vs2022调试基础篇【由浅入深-C语言】
c语言
ceclar1231 天前
C++范围操作(2)
开发语言·c++
一个不知名程序员www1 天前
算法学习入门---vector(C++)
c++·算法
明洞日记1 天前
【数据结构手册002】动态数组vector - 连续内存的艺术与科学
开发语言·数据结构·c++