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
相关推荐
conti12312 小时前
水题记录2.4
c++·笔记·题解
ShineWinsu12 小时前
C++技术文章
开发语言·c++
星星码️12 小时前
C++选择题练习(二)
c++
✎ ﹏梦醒͜ღ҉繁华落℘12 小时前
Makefile(四)--gcc 和gdb
c语言·gnu·gcc和gdb
white-persist12 小时前
逆向入门经典题:从 IDA 反编译坑点到 Python 解题详细分析解释
c语言·开发语言·数据结构·python·算法·逆向·安全架构
誰能久伴不乏12 小时前
SPI总线通信协议基础与ICM20607传感器驱动开发指南
arm开发·c++·驱动开发·嵌入式硬件·arm
十五年专注C++开发13 小时前
HDF5: 大数据的 “超级容器“
大数据·数据库·c++·hdf5
白玉cfc13 小时前
OC底层原理:alloc&init&new
c++·macos·ios·objective-c·xcode
-凌凌漆-13 小时前
【QML】qml和C++中同时使用单例模式
java·c++·单例模式
6Hzlia13 小时前
【Hot 100 刷题计划】 LeetCode 101. 对称二叉树 | C++ DFS 极简递归模板
c++·leetcode·深度优先