C++中protobuf Message与JSON的互相转换
环境:
protobuf: v27.3(2024-08-01)
abseil: 20240722.0
文章目录
- C++中protobuf Message与JSON的互相转换
- 前言
- 1. 编写通讯录addressbook.proto
- 2. 编译
- 3. C++中测试protobuf与json的转换
- 4. 结果
前言
PB转JSON:Protocol Buffers的Message对象转换为 JSON 格式字符串
JSON转PB:JSON格式字符串解析为 Protocol Buffers 的Message对象
protobuf中可以通过MessageToJsonString和JsonStringToMessage函数完成上述转换。
注意:MessageToJsonString和JsonStringToMessage函数仅支持Message对象,不支持MessageLite对象(后面会介绍MessageLite和JSON的转换)。
1. 编写通讯录addressbook.proto
syntax = "proto3";package com.test;message Person {string name = 1;int32 age = 2;string phone = 3;
}message AddressBook{repeated Person people = 1;
}
2. 编译
protoc -I=. --cpp_out=. addressbook.proto
tree
.
+--- addressbook.pb.cc
+--- addressbook.pb.h
+--- addressbook.proto
+--- protoc.exe
3. C++中测试protobuf与json的转换
main.cpp
#include <iostream>#include <google/protobuf/util/json_util.h> // MessageToJsonString JsonStringToMessage#include "addressbook.pb.h"int main(int argc, char *argv[])
{com::test::AddressBook addressbook1;com::test::Person* person1 = addressbook1.add_people();person1->set_name("xiaoming");person1->set_age(30);person1->set_phone("13012345678");// PB to JSONstd::string result1;google::protobuf::json::MessageToJsonString(addressbook1, &result1);std::cout << "AddressBook From PB - " << result1 << std::endl;// JSON to PBstd::string jsonStr = R"({"people":[{"name":"xiaohong","age":31,"phone":"13112345678"}]})";com::test::AddressBook addressbook2;google::protobuf::json::JsonStringToMessage(jsonStr, &addressbook2);std::string result2;google::protobuf::json::MessageToJsonString(addressbook2, &result2);std::cout << "AddressBook From JSON - " << result2 << std::endl;getchar();return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)project(main)include_directories(.) # addressbook.pb.h# protobuf
add_definitions(-DPROTOBUF_USE_DLLS)
include_directories(include)
link_directories(lib)add_executable(${PROJECT_NAME} main.cpp addressbook.pb.cc)target_link_libraries(${PROJECT_NAME} libprotobuf abseil_dll)
目录结构
tree
.
+--- include
+--- lib
+--- addressbook.pb.cc
+--- addressbook.pb.h
+--- addressBook.proto
+--- CMakeLists.txt
+--- main.cpp
4. 结果
AddressBook From PB - {"people":[{"name":"xiaoming","age":30,"phone":"13012345678"}]}
AddressBook From Json - {"people":[{"name":"xiaohong","age":31,"phone":"13112345678"}]}