Android Protobuf JSON 序列化和反序列化库
#include <jsonpb/jsonpb.h> #include <android-base/logging.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include <google/protobuf/util/json_util.h> #include <google/protobuf/util/type_resolver_util.h>
namespace android { namespace jsonpb {
using google::protobuf::DescriptorPool; using google::protobuf::Message; using google::protobuf::util::NewTypeResolverForDescriptorPool; using google::protobuf::util::TypeResolver;
static constexpr char kTypeUrlPrefix[] = "type.googleapis.com";
std::string GetTypeUrl(const Message& message) { return std::string(kTypeUrlPrefix) + "/" + message.GetDescriptor()->full_name(); }
ErrorOrstd::string MessageToJsonString(const Message& message) {
std::unique_ptr
google::protobuf::util::JsonOptions options; options.add_whitespace = true;
std::string json; auto status = google::protobuf::util::MessageToJsonString(message, &json, options, resolver.get());
if (!status.ok()) { return MakeErrorstd::string(status.message()); }
return ErrorOrstd::string(std::move(json)); }
namespace internal {
ErrorOrstd::monostate JsonStringToMessage(const std::string& content, Message* message) {
std::unique_ptr
google::protobuf::util::JsonParseOptions options; auto status = google::protobuf::util::JsonStringToMessage(content, message, options, resolver.get());
if (!status.ok()) { return MakeErrorstd::string(status.message()); }
return ErrorOrstd::monostate(); }
} // namespace internal
} // namespace jsonpb } // namespace android
// 修复了 MessageToJsonString 和 JsonStringToMessage 函数。使用了 protobuf 提供的函数进行编码和解码。
原文地址: https://www.cveoy.top/t/topic/m2xV 著作权归作者所有。请勿转载和采集!