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
相关推荐
LaoWaiHang3 分钟前
C语言从头学61——学习头文件signal.h
c语言
Antonio91517 分钟前
【CMake】使用CMake在Visual Studio内构建多文件夹工程
开发语言·c++·visual studio
LyaJpunov31 分钟前
C++中move和forword的区别
开发语言·c++
程序猿练习生36 分钟前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
z千鑫44 分钟前
【人工智能】如何利用AI轻松将java,c++等代码转换为Python语言?程序员必读
java·c++·人工智能·gpt·agent·ai编程·ai工具
林戈的IT生涯44 分钟前
MySQL5.7中增加的JSON特性的处理方法JSON_EXTRACT和JSON_ARRAY_APPEND以及MYSQL中JSON操作的方法大全
json·mysql5.7·json特性·json_extract·mysql中json操作方法
一名路过的小码农1 小时前
C/C++动态库函数导出 windows
c语言·开发语言·c++
m0_631270401 小时前
标准c语言(一)
c语言·开发语言·算法
万河归海4281 小时前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
小周的C语言学习笔记1 小时前
鹏哥C语言36-37---循环/分支语句练习(折半查找算法)
c语言·算法·visual studio