1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <string> 20 21 #include <jsonpb/error_or.h> 22 23 #include <google/protobuf/message.h> 24 25 namespace android { 26 namespace jsonpb { 27 28 namespace internal { 29 ErrorOr<std::monostate> JsonStringToMessage(const std::string& content, 30 google::protobuf::Message* message); 31 } // namespace internal 32 33 // TODO: JsonStringToMessage is a newly added function in protobuf 34 // and is not yet available in the android tree. Replace this function with 35 // https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.util.json_util#JsonStringToMessage.details 36 // when the android tree gets updated 37 template <typename T> JsonStringToMessage(const std::string & content)38ErrorOr<T> JsonStringToMessage(const std::string& content) { 39 ErrorOr<T> ret; 40 auto error = internal::JsonStringToMessage(content, &*ret); 41 if (!error.ok()) { 42 return MakeError<T>(error.error()); 43 } 44 return ret; 45 } 46 47 // TODO: MessageToJsonString is a newly added function in protobuf 48 // and is not yet available in the android tree. Replace this function with 49 // https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.util.json_util#MessageToJsonString.details 50 // when the android tree gets updated. 51 // 52 // The new MessageToJsonString also allows preserving proto field names. However, 53 // the function here can't. Hence, a field name "foo_bar" without json_name option 54 // will be "fooBar" in the final output. Additional checks are needed to ensure 55 // that doesn't happen. 56 ErrorOr<std::string> MessageToJsonString(const google::protobuf::Message& message); 57 58 } // namespace jsonpb 59 } // namespace android 60