1.介绍
#include <google/protobuf/util/json_util.h> // 需要包含该头文件
#include "proto/message.pb.h"
// proto文件
syntax="proto3";
package mymessage;
message MyPbTest{
uint32 id = 1;
repeated string keys = 2;
string cc = 3;
};
using namespace std;
int main(int argc, char const *argv[])
{
mymessage::MyPbTest pbtest;
pbtest.set_id(6);
pbtest.add_keys("AB");
pbtest.add_keys("BC");
cout<<pbtest.ShortDebugString()<<endl;
string str;
google::protobuf::util::JsonPrintOptions options;
// options.add_whitespace = true; // 会以json文件的格式显示,有排版
options.always_print_primitive_fields = true; // 保证就算字段未设置,也会打印该字段,并且是默认值
options.preserve_proto_field_names = true;
google::protobuf::util::MessageToJsonString(pbtest, &str, options);
cout<<str;
cout<<endl;
return 0;
}
// 运行结果
id: 6 keys: "AB" keys: "BC"
{"id":6,"keys":["AB","BC"],"cc":""}