xref: /aosp_15_r20/external/protobuf/src/google/protobuf/util/json_util.h (revision 1b3f573f81763fcece89efc2b6a5209149e44ab8)
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Utility functions to convert between protobuf binary format and proto3 JSON
32 // format.
33 #ifndef GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__
34 #define GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__
35 
36 #include <google/protobuf/stubs/bytestream.h>
37 #include <google/protobuf/stubs/status.h>
38 #include <google/protobuf/stubs/strutil.h>
39 #include <google/protobuf/message.h>
40 #include <google/protobuf/util/type_resolver.h>
41 
42 // Must be included last.
43 #include <google/protobuf/port_def.inc>
44 
45 namespace google {
46 namespace protobuf {
47 namespace io {
48 class ZeroCopyInputStream;
49 class ZeroCopyOutputStream;
50 }  // namespace io
51 namespace util {
52 
53 struct JsonParseOptions {
54   // Whether to ignore unknown JSON fields during parsing
55   bool ignore_unknown_fields;
56 
57   // If true, when a lowercase enum value fails to parse, try convert it to
58   // UPPER_CASE and see if it matches a valid enum.
59   // WARNING: This option exists only to preserve legacy behavior. Avoid using
60   // this option. If your enum needs to support different casing, consider using
61   // allow_alias instead.
62   bool case_insensitive_enum_parsing;
63 
JsonParseOptionsJsonParseOptions64   JsonParseOptions()
65       : ignore_unknown_fields(false), case_insensitive_enum_parsing(false) {}
66 };
67 
68 struct JsonPrintOptions {
69   // Whether to add spaces, line breaks and indentation to make the JSON output
70   // easy to read.
71   bool add_whitespace;
72   // Whether to always print primitive fields. By default proto3 primitive
73   // fields with default values will be omitted in JSON output. For example, an
74   // int32 field set to 0 will be omitted. Set this flag to true will override
75   // the default behavior and print primitive fields regardless of their values.
76   bool always_print_primitive_fields;
77   // Whether to always print enums as ints. By default they are rendered as
78   // strings.
79   bool always_print_enums_as_ints;
80   // Whether to preserve proto field names
81   bool preserve_proto_field_names;
82 
JsonPrintOptionsJsonPrintOptions83   JsonPrintOptions()
84       : add_whitespace(false),
85         always_print_primitive_fields(false),
86         always_print_enums_as_ints(false),
87         preserve_proto_field_names(false) {}
88 };
89 
90 // DEPRECATED. Use JsonPrintOptions instead.
91 typedef JsonPrintOptions JsonOptions;
92 
93 // Converts from protobuf message to JSON and appends it to |output|. This is a
94 // simple wrapper of BinaryToJsonString(). It will use the DescriptorPool of the
95 // passed-in message to resolve Any types.
96 PROTOBUF_EXPORT util::Status MessageToJsonString(const Message& message,
97                                                  std::string* output,
98                                                  const JsonOptions& options);
99 
MessageToJsonString(const Message & message,std::string * output)100 inline util::Status MessageToJsonString(const Message& message,
101                                         std::string* output) {
102   return MessageToJsonString(message, output, JsonOptions());
103 }
104 
105 // Converts from JSON to protobuf message. This is a simple wrapper of
106 // JsonStringToBinary(). It will use the DescriptorPool of the passed-in
107 // message to resolve Any types.
108 PROTOBUF_EXPORT util::Status JsonStringToMessage(
109     StringPiece input, Message* message, const JsonParseOptions& options);
110 
JsonStringToMessage(StringPiece input,Message * message)111 inline util::Status JsonStringToMessage(StringPiece input,
112                                         Message* message) {
113   return JsonStringToMessage(input, message, JsonParseOptions());
114 }
115 
116 // Converts protobuf binary data to JSON.
117 // The conversion will fail if:
118 //   1. TypeResolver fails to resolve a type.
119 //   2. input is not valid protobuf wire format, or conflicts with the type
120 //      information returned by TypeResolver.
121 // Note that unknown fields will be discarded silently.
122 PROTOBUF_EXPORT util::Status BinaryToJsonStream(
123     TypeResolver* resolver, const std::string& type_url,
124     io::ZeroCopyInputStream* binary_input,
125     io::ZeroCopyOutputStream* json_output, const JsonPrintOptions& options);
126 
BinaryToJsonStream(TypeResolver * resolver,const std::string & type_url,io::ZeroCopyInputStream * binary_input,io::ZeroCopyOutputStream * json_output)127 inline util::Status BinaryToJsonStream(TypeResolver* resolver,
128                                        const std::string& type_url,
129                                        io::ZeroCopyInputStream* binary_input,
130                                        io::ZeroCopyOutputStream* json_output) {
131   return BinaryToJsonStream(resolver, type_url, binary_input, json_output,
132                             JsonPrintOptions());
133 }
134 
135 PROTOBUF_EXPORT util::Status BinaryToJsonString(
136     TypeResolver* resolver, const std::string& type_url,
137     const std::string& binary_input, std::string* json_output,
138     const JsonPrintOptions& options);
139 
BinaryToJsonString(TypeResolver * resolver,const std::string & type_url,const std::string & binary_input,std::string * json_output)140 inline util::Status BinaryToJsonString(TypeResolver* resolver,
141                                        const std::string& type_url,
142                                        const std::string& binary_input,
143                                        std::string* json_output) {
144   return BinaryToJsonString(resolver, type_url, binary_input, json_output,
145                             JsonPrintOptions());
146 }
147 
148 // Converts JSON data to protobuf binary format.
149 // The conversion will fail if:
150 //   1. TypeResolver fails to resolve a type.
151 //   2. input is not valid JSON format, or conflicts with the type
152 //      information returned by TypeResolver.
153 PROTOBUF_EXPORT util::Status JsonToBinaryStream(
154     TypeResolver* resolver, const std::string& type_url,
155     io::ZeroCopyInputStream* json_input,
156     io::ZeroCopyOutputStream* binary_output, const JsonParseOptions& options);
157 
JsonToBinaryStream(TypeResolver * resolver,const std::string & type_url,io::ZeroCopyInputStream * json_input,io::ZeroCopyOutputStream * binary_output)158 inline util::Status JsonToBinaryStream(
159     TypeResolver* resolver, const std::string& type_url,
160     io::ZeroCopyInputStream* json_input,
161     io::ZeroCopyOutputStream* binary_output) {
162   return JsonToBinaryStream(resolver, type_url, json_input, binary_output,
163                             JsonParseOptions());
164 }
165 
166 PROTOBUF_EXPORT util::Status JsonToBinaryString(
167     TypeResolver* resolver, const std::string& type_url,
168     StringPiece json_input, std::string* binary_output,
169     const JsonParseOptions& options);
170 
JsonToBinaryString(TypeResolver * resolver,const std::string & type_url,StringPiece json_input,std::string * binary_output)171 inline util::Status JsonToBinaryString(TypeResolver* resolver,
172                                        const std::string& type_url,
173                                        StringPiece json_input,
174                                        std::string* binary_output) {
175   return JsonToBinaryString(resolver, type_url, json_input, binary_output,
176                             JsonParseOptions());
177 }
178 
179 namespace internal {
180 // Internal helper class. Put in the header so we can write unit-tests for it.
181 class PROTOBUF_EXPORT ZeroCopyStreamByteSink : public strings::ByteSink {
182  public:
ZeroCopyStreamByteSink(io::ZeroCopyOutputStream * stream)183   explicit ZeroCopyStreamByteSink(io::ZeroCopyOutputStream* stream)
184       : stream_(stream), buffer_(nullptr), buffer_size_(0) {}
185   ~ZeroCopyStreamByteSink() override;
186 
187   void Append(const char* bytes, size_t len) override;
188 
189  private:
190   io::ZeroCopyOutputStream* stream_;
191   void* buffer_;
192   int buffer_size_;
193 
194   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyStreamByteSink);
195 };
196 }  // namespace internal
197 
198 }  // namespace util
199 }  // namespace protobuf
200 }  // namespace google
201 
202 #include <google/protobuf/port_undef.inc>
203 
204 #endif  // GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__
205