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
相关推荐
jikiecui6 小时前
信奥崔老师:实数型: float、double
c++·算法
GilgameshJSS6 小时前
STM32H743-ARM例程26-TCP_CLIENT
c语言·arm开发·stm32·单片机·tcp/ip
Source.Liu6 小时前
【CMakeLists.txt】CMake 编译定义带值参数详解
c++·qt·librecad
杨福瑞6 小时前
数据结构:顺序表讲解(1)
c语言·开发语言·数据结构
程序猿编码7 小时前
轻量级却实用:sigtrace 如何靠 ptrace 实现 Linux 信号的捕获与阻断(C/C++代码实现)
linux·c语言·c++·信号·捕获·ptrace
曦樂~7 小时前
【Qt】TCP连接--客户端和服务器
服务器·网络·c++·qt·tcp/ip
WoodWall7 小时前
WebServer 02 Reactor模式
c++·后端
WaWaJie_Ngen7 小时前
【OpenGL】模板测试(StencilTest)
c++·算法·游戏·游戏引擎·游戏程序·图形渲染
滴_咕噜咕噜7 小时前
【MFC】数据库操作:数据库动态生成
数据库·c++·mfc
WoodWall7 小时前
WebServer 00 重要前置知识
c++·后端