-
测试环境
- ubuntu16.04 64bit
- protocbuf:3.9.1 (支持json转换需>=3.0.0)
-
协议
cppsyntax = "proto2"; message Person{ optional string name = 1; optional uint32 age = 2; optional string address = 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; }
-
编译
-
编译协议
powershellprotoc --cpp_out=. person.proto
-
编译代码
powershellg++ person.pb.cc demo.cpp -lprotobuf -lpthread -o demo && ./demo
-
-
运行结果
powershellpb to json:{"name":"hb","age":20,"address":"sjz"} json to pb: name:HB age:22 address:SJZ
C/C++ protobuf与json互转
韩搏2024-01-26 23:00
相关推荐
网络安全研发随想2 分钟前
C语言核心结构+难点精讲+工程技巧别来无恙2028 分钟前
数据结构(6)superior tigre15 分钟前
C++学习:六个月从基础到就业——面向对象编程:虚函数与抽象类superior tigre1 小时前
C++学习:六个月从基础到就业——面向对象编程:重载运算符(下)海棠蚀omo1 小时前
C++笔记-list烟雨柳成烟1 小时前
C++学习Day0:c++简介XINVRY-FPGA1 小时前
XC6SLX100T-2FGG484I 赛灵思 XilinxFPGA Spartan-6SMiLe2 小时前
CMake学习笔记末央&2 小时前
【C++】特化妙技与分文件编写 “雷区”暖阳华笺3 小时前
Leetcode刷题 由浅入深之哈希表——242. 有效的字母异位词