1 // Copyright 2020 Google Inc.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 ////////////////////////////////////////////////////////////////////////////////
17 #include "json_proto_converter.h"
19 namespace json_proto {
21 void JsonProtoConverter::AppendArray(const ArrayValue& array_value) {
23 bool need_comma = false;
24 for (const auto& value : array_value.value()) {
25 // Trailing comma inside of an array makes JSON invalid, avoid adding that.
36 void JsonProtoConverter::AppendNumber(const NumberValue& number_value) {
37 if (number_value.has_float_value()) {
38 data_ << number_value.float_value().value();
39 } else if (number_value.has_exponent_value()) {
40 auto value = number_value.exponent_value();
41 data_ << value.base();
42 data_ << (value.use_uppercase() ? 'E' : 'e');
43 data_ << value.exponent();
44 } else if (number_value.has_exponent_frac_value()) {
45 auto value = number_value.exponent_value();
46 data_ << value.base();
47 data_ << (value.use_uppercase() ? 'E' : 'e');
48 data_ << value.exponent();
50 data_ << number_value.integer_value().value();
54 void JsonProtoConverter::AppendObject(const JsonObject& json_object) {
55 data_ << '{' << '"' << json_object.name() << '"' << ':';
56 AppendValue(json_object.value());
60 void JsonProtoConverter::AppendValue(const JsonValue& json_value) {
61 if (json_value.has_object_value()) {
62 AppendObject(json_value.object_value());
63 } else if (json_value.has_array_value()) {
64 AppendArray(json_value.array_value());
65 } else if (json_value.has_number_value()) {
66 AppendNumber(json_value.number_value());
67 } else if (json_value.has_string_value()) {
68 data_ << '"' << json_value.string_value().value() << '"';
69 } else if (json_value.has_boolean_value()) {
70 data_ << (json_value.boolean_value().value() ? "true" : "false");
76 std::string JsonProtoConverter::Convert(const JsonObject& json_object) {
77 AppendObject(json_object);
81 std::string JsonProtoConverter::Convert(
82 const json_proto::ArrayValue& json_array) {
83 AppendArray(json_array);
87 } // namespace json_proto