xref: /aosp_15_r20/external/grpc-grpc/test/cpp/qps/parse_json.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2016 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include "test/cpp/qps/parse_json.h"
20 
21 #include <string>
22 
23 #include "absl/strings/str_format.h"
24 
25 #include <grpc/support/log.h>
26 
27 #include "src/core/lib/gprpp/crash.h"
28 
29 namespace grpc {
30 namespace testing {
31 
ParseJson(const std::string & json,const std::string & type,GRPC_CUSTOM_MESSAGE * msg)32 void ParseJson(const std::string& json, const std::string& type,
33                GRPC_CUSTOM_MESSAGE* msg) {
34   std::unique_ptr<protobuf::json::TypeResolver> type_resolver(
35       protobuf::json::NewTypeResolverForDescriptorPool(
36           "type.googleapis.com", protobuf::DescriptorPool::generated_pool()));
37   std::string binary;
38   auto status = JsonToBinaryString(
39       type_resolver.get(), "type.googleapis.com/" + type, json, &binary);
40   if (!status.ok()) {
41     std::string errmsg(status.message());
42     gpr_log(GPR_ERROR, "Failed to convert json to binary: errcode=%d msg=%s",
43             static_cast<int>(status.code()), errmsg.c_str());
44     grpc_core::Crash(absl::StrFormat("JSON: %s", json.c_str()));
45   }
46   GPR_ASSERT(msg->ParseFromString(binary));
47 }
48 
SerializeJson(const GRPC_CUSTOM_MESSAGE & msg,const std::string & type)49 std::string SerializeJson(const GRPC_CUSTOM_MESSAGE& msg,
50                           const std::string& type) {
51   std::unique_ptr<protobuf::json::TypeResolver> type_resolver(
52       protobuf::json::NewTypeResolverForDescriptorPool(
53           "type.googleapis.com", protobuf::DescriptorPool::generated_pool()));
54   std::string binary;
55   std::string json_string;
56   msg.SerializeToString(&binary);
57   auto status =
58       BinaryToJsonString(type_resolver.get(), type, binary, &json_string);
59   GPR_ASSERT(status.ok());
60   return json_string;
61 }
62 
63 }  // namespace testing
64 }  // namespace grpc
65