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
相关推荐
码农编程录17 分钟前
【c/c++3】类和对象,vector容器,类继承和多态,systemd,std&boost
c++
??tobenewyorker2 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
oioihoii3 小时前
C++11 forward_list 从基础到精通:原理、实践与性能优化
c++·性能优化·list
m0_687399843 小时前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg
Natsume17103 小时前
嵌入式开发:GPIO、UART、SPI、I2C 驱动开发详解与实战案例
c语言·驱动开发·stm32·嵌入式硬件·mcu·架构·github
shaun20013 小时前
华为c编程规范
c语言
MeshddY4 小时前
(超详细)数据库项目初体验:使用C语言连接数据库完成短地址服务(本地运行版)
c语言·数据库·单片机
森焱森4 小时前
无人机三轴稳定化控制(1)____飞机的稳定控制逻辑
c语言·单片机·算法·无人机
Ronin3054 小时前
【C++】类型转换
开发语言·c++
mrbone114 小时前
Git-git worktree的使用
开发语言·c++·git·cmake·worktree·gitab