parse_json.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #include "test/cpp/qps/parse_json.h"
  19. #include <string>
  20. #include <grpc/support/log.h>
  21. namespace grpc {
  22. namespace testing {
  23. void ParseJson(const std::string& json, const std::string& type,
  24. GRPC_CUSTOM_MESSAGE* msg) {
  25. std::unique_ptr<protobuf::json::TypeResolver> type_resolver(
  26. protobuf::json::NewTypeResolverForDescriptorPool(
  27. "type.googleapis.com", protobuf::DescriptorPool::generated_pool()));
  28. std::string binary;
  29. auto status = JsonToBinaryString(
  30. type_resolver.get(), "type.googleapis.com/" + type, json, &binary);
  31. if (!status.ok()) {
  32. std::string errmsg(status.message());
  33. gpr_log(GPR_ERROR, "Failed to convert json to binary: errcode=%d msg=%s",
  34. status.code(), errmsg.c_str());
  35. gpr_log(GPR_ERROR, "JSON: %s", json.c_str());
  36. abort();
  37. }
  38. GPR_ASSERT(msg->ParseFromString(binary));
  39. }
  40. std::string SerializeJson(const GRPC_CUSTOM_MESSAGE& msg,
  41. const std::string& type) {
  42. std::unique_ptr<protobuf::json::TypeResolver> type_resolver(
  43. protobuf::json::NewTypeResolverForDescriptorPool(
  44. "type.googleapis.com", protobuf::DescriptorPool::generated_pool()));
  45. std::string binary;
  46. std::string json_string;
  47. msg.SerializeToString(&binary);
  48. auto status =
  49. BinaryToJsonString(type_resolver.get(), type, binary, &json_string);
  50. GPR_ASSERT(status.ok());
  51. return json_string;
  52. }
  53. } // namespace testing
  54. } // namespace grpc