小弧光的博客

公众号:小弧光黑板报

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

protobuf 和 json 互转

common.h

#ifndef COMMON_H
#define COMMON_H
#include "google/protobuf/message.h"
#include "nlohmann/json.hpp"
#include "google/protobuf/util/json_util.h"
using google::protobuf::util::MessageToJsonString;
using namespace google::protobuf::util;
google::protobuf::util::JsonOptions JsonOption();
google::protobuf::util::JsonParseOptions JsonParseOption();
nlohmann::json ProtoToJson(const google::protobuf::Message &proto);
int JsonToProto(const std::string& strJson, google::protobuf::Message *proto);
#endif

common.cpp

#include "common.h"
google::protobuf::util::JsonOptions JsonOption()
{
google::protobuf::util::JsonOptions json_option;
json_option.always_print_primitive_fields = true;
return json_option;
}
google::protobuf::util::JsonParseOptions JsonParseOption()
{
google::protobuf::util::JsonParseOptions json_option;
json_option.ignore_unknown_fields = true;
return json_option;
}
nlohmann::json ProtoToJson(const google::protobuf::Message &proto)
{
static const auto kJsonOption = JsonOption();
std::string json_string;
const auto status = MessageToJsonString(proto, &json_string, kJsonOption);
nlohmann::json json_obj = nlohmann::json::parse(json_string);
return json_obj;
}
int JsonToProto(const std::string& strJson, google::protobuf::Message *proto)
{
static const auto kJsonParseOption = JsonParseOption();
const auto status = JsonStringToMessage(strJson, proto, kJsonParseOption);
return 0;
}

posted on   小弧光  阅读(186)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示