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 18 #pragma once 19 20 #include <string> 21 22 #include <jsonpb/error_or.h> 23 24 #include <google/protobuf/message.h> 25 26 namespace android { 27 namespace jsonpb { 28 29 namespace internal { 30 ErrorOr<std::monostate> JsonStringToMessage(const std::string& content, 31 google::protobuf::Message* message); 32 } // namespace internal 33 34 // TODO: JsonStringToMessage is a newly added function in protobuf 35 // and is not yet available in the android tree. Replace this function with 36 // https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.util.json_util#JsonStringToMessage.details 37 // when the android tree gets updated 38 template <typename T> JsonStringToMessage(const std::string & content)39ErrorOr<T> JsonStringToMessage(const std::string& content) { 40 ErrorOr<T> ret; 41 auto error = internal::JsonStringToMessage(content, &*ret); 42 if (!error.ok()) { 43 return MakeError<T>(error.error()); 44 } 45 return ret; 46 } 47 48 // TODO: MessageToJsonString is a newly added function in protobuf 49 // and is not yet available in the android tree. Replace this function with 50 // https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.util.json_util#MessageToJsonString.details 51 // when the android tree gets updated. 52 // 53 // The new MessageToJsonString also allows preserving proto field names. However, 54 // the function here can't. Hence, a field name "foo_bar" without json_name option 55 // will be "fooBar" in the final output. Additional checks are needed to ensure 56 // that doesn't happen. 57 ErrorOr<std::string> MessageToJsonString(const google::protobuf::Message& message); 58 59 } // namespace jsonpb 60 } // namespace android 61