Protocol buffer v3声称,该库是json友好的(https://developers.google.com/protocol-buffers/docs/proto3#json),但我找不到如何实现这种映射。我应该在协议中添加一些插件,或者一些选项,或者调用一些特殊的东西来代替SerializeTo/ParseFrom吗?
是使用该功能的人吗?
发布于 2017-06-01 01:37:04
我使用的是Protobuf 3.3.0,它有一个内置的JSON序列化和解析器。您可以使用来自google/protobuf/util/json_util.h的两个函数,即MessageToJsonString()和JsonStringToMessage(),使您的C++生成的Message对象分别来往于JSON。
下面是一个使用它们的简单测试:test-protobuf.proto
syntax = "proto3";
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}test-protobuf.cpp
#include <iostream>
#include <google/protobuf/util/json_util.h>
#include "test-protobuf.pb.h"
int main()
{
std::string json_string;
SearchRequest sr, sr2;
// Populate sr.
sr.set_query(std::string("Hello!"));
sr.set_page_number(1);
sr.set_result_per_page(10);
// Create a json_string from sr.
google::protobuf::util::JsonPrintOptions options;
options.add_whitespace = true;
options.always_print_primitive_fields = true;
options.preserve_proto_field_names = true;
MessageToJsonString(sr, &json_string, options);
// Print json_string.
std::cout << json_string << std::endl;
// Parse the json_string into sr2.
google::protobuf::util::JsonParseOptions options2;
JsonStringToMessage(json_string, &sr2, options2);
// Print the values of sr2.
std::cout
<< sr2.query() << ", "
<< sr2.page_number() << ", "
<< sr2.result_per_page() << std::endl
;
return 0;
}您可以使用以下CMakeLists.txt文件(在Windows上测试)编译这些文件(假设您已经安装了protobuf、编译器和CMake )。
cmake_minimum_required(VERSION 3.8)
project(test-protobuf)
find_package(Protobuf REQUIRED)
# Use static runtime for MSVC
if(MSVC)
foreach(flag_var
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif(${flag_var} MATCHES "/MD")
endforeach(flag_var)
endif(MSVC)
protobuf_generate_cpp(test-protobuf-sources test-protobuf-headers
"${CMAKE_CURRENT_LIST_DIR}/test-protobuf.proto"
)
list(APPEND test-protobuf-sources
"${CMAKE_CURRENT_LIST_DIR}/test-protobuf.cpp"
)
add_executable(test-protobuf ${test-protobuf-sources} ${test-protobuf-headers})
target_include_directories(test-protobuf
PUBLIC
${PROTOBUF_INCLUDE_DIRS}
${CMAKE_CURRENT_BINARY_DIR}
)
target_link_libraries(test-protobuf
${PROTOBUF_LIBRARIES}
)假设CMakeLists.txt、test-protobuf.proto和test-protobuf.cpp在同一个目录中,下面是使用Visual Studio15 2017和64位protobuf库在Windows上编译和运行它们的命令。
mkdir build
cd build
cmake -G "Visual Studio 15 2017 Win64" ..
cmake --build . --config Release
Release/test-protobuf您应该会看到以下输出:
{
"query": "Hello!",
"page_number": 1,
"result_per_page": 10
}
Hello!, 1, 10发布于 2016-01-21 01:58:50
Protobuf有针对C#的json api。在google protobuf reference中有一些用于C#的json类,您可以在github protobuf repository中找到一些用于java和c++的测试。
https://stackoverflow.com/questions/34906305
复制相似问题