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/message.h>
37 #include <google/protobuf/util/type_resolver.h>
38 #include <google/protobuf/stubs/bytestream.h>
39 #include <google/protobuf/stubs/strutil.h>
40 
41 #include <google/protobuf/port_def.inc>
42 
43 namespace google {
44 namespace protobuf {
45 namespace io {
46 class ZeroCopyInputStream;
47 class ZeroCopyOutputStream;
48 }  // namespace io
49 namespace util {
50 
51 struct JsonParseOptions {
52   // Whether to ignore unknown JSON fields during parsing
53   bool ignore_unknown_fields;
54 
55   // If true, when a lowercase enum value fails to parse, try convert it to
56   // UPPER_CASE and see if it matches a valid enum.
57   // WARNING: This option exists only to preserve legacy behavior. Avoid using
58   // this option. If your enum needs to support different casing, consider using
59   // allow_alias instead.
60   bool case_insensitive_enum_parsing;
61 
JsonParseOptionsJsonParseOptions62   JsonParseOptions()
63       : ignore_unknown_fields(false),
64         case_insensitive_enum_parsing(false) {}
65 };
66 
67 struct JsonPrintOptions {
68   // Whether to add spaces, line breaks and indentation to make the JSON output
69   // easy to read.
70   bool add_whitespace;
71   // Whether to always print primitive fields. By default proto3 primitive
72   // fields with default values will be omitted in JSON output. For example, an
73   // int32 field set to 0 will be omitted. Set this flag to true will override
74   // the default behavior and print primitive fields regardless of their values.
75   bool always_print_primitive_fields;
76   // Whether to always print enums as ints. By default they are rendered as
77   // strings.
78   bool always_print_enums_as_ints;
79   // Whether to preserve proto field names
80   bool preserve_proto_field_names;
81 
JsonPrintOptionsJsonPrintOptions82   JsonPrintOptions()
83       : add_whitespace(false),
84         always_print_primitive_fields(false),
85         always_print_enums_as_ints(false),
86         preserve_proto_field_names(false) {}
87 };
88 
89 // DEPRECATED. Use JsonPrintOptions instead.
90 typedef JsonPrintOptions JsonOptions;
91 
92 // Converts from protobuf message to JSON and appends it to |output|. This is a
93 // simple wrapper of BinaryToJsonString(). It will use the DescriptorPool of the
94 // passed-in message to resolve Any types.
95 PROTOBUF_EXPORT util::Status MessageToJsonString(const Message& message,
96                                                    std::string* output,
97                                                    const JsonOptions& options);
98 
MessageToJsonString(const Message & message,std::string * output)99 inline util::Status MessageToJsonString(const Message& message,
100                                           std::string* output) {
101   return MessageToJsonString(message, output, JsonOptions());
102 }
103 
104 // Converts from JSON to protobuf message. This is a simple wrapper of
105 // JsonStringToBinary(). It will use the DescriptorPool of the passed-in
106 // message to resolve Any types.
107 PROTOBUF_EXPORT util::Status JsonStringToMessage(
108     StringPiece input, Message* message, const JsonParseOptions& options);
109 
JsonStringToMessage(StringPiece input,Message * message)110 inline util::Status JsonStringToMessage(StringPiece input,
111                                           Message* message) {
112   return JsonStringToMessage(input, message, JsonParseOptions());
113 }
114 
115 // Converts protobuf binary data to JSON.
116 // The conversion will fail if:
117 //   1. TypeResolver fails to resolve a type.
118 //   2. input is not valid protobuf wire format, or conflicts with the type
119 //      information returned by TypeResolver.
120 // Note that unknown fields will be discarded silently.
121 PROTOBUF_EXPORT util::Status BinaryToJsonStream(
122     TypeResolver* resolver, const std::string& type_url,
123     io::ZeroCopyInputStream* binary_input,
124     io::ZeroCopyOutputStream* json_output, const JsonPrintOptions& options);
125 
BinaryToJsonStream(TypeResolver * resolver,const std::string & type_url,io::ZeroCopyInputStream * binary_input,io::ZeroCopyOutputStream * json_output)126 inline util::Status BinaryToJsonStream(
127     TypeResolver* resolver, const std::string& type_url,
128     io::ZeroCopyInputStream* binary_input,
129     io::ZeroCopyOutputStream* json_output) {
130   return BinaryToJsonStream(resolver, type_url, binary_input, json_output,
131                             JsonPrintOptions());
132 }
133 
134 PROTOBUF_EXPORT util::Status BinaryToJsonString(
135     TypeResolver* resolver, const std::string& type_url,
136     const std::string& binary_input, std::string* json_output,
137     const JsonPrintOptions& options);
138 
BinaryToJsonString(TypeResolver * resolver,const std::string & type_url,const std::string & binary_input,std::string * json_output)139 inline util::Status BinaryToJsonString(TypeResolver* resolver,
140                                          const std::string& type_url,
141                                          const std::string& binary_input,
142                                          std::string* json_output) {
143   return BinaryToJsonString(resolver, type_url, binary_input, json_output,
144                             JsonPrintOptions());
145 }
146 
147 // Converts JSON data to protobuf binary format.
148 // The conversion will fail if:
149 //   1. TypeResolver fails to resolve a type.
150 //   2. input is not valid JSON format, or conflicts with the type
151 //      information returned by TypeResolver.
152 PROTOBUF_EXPORT util::Status JsonToBinaryStream(
153     TypeResolver* resolver, const std::string& type_url,
154     io::ZeroCopyInputStream* json_input,
155     io::ZeroCopyOutputStream* binary_output, const JsonParseOptions& options);
156 
JsonToBinaryStream(TypeResolver * resolver,const std::string & type_url,io::ZeroCopyInputStream * json_input,io::ZeroCopyOutputStream * binary_output)157 inline util::Status JsonToBinaryStream(
158     TypeResolver* resolver, const std::string& type_url,
159     io::ZeroCopyInputStream* json_input,
160     io::ZeroCopyOutputStream* binary_output) {
161   return JsonToBinaryStream(resolver, type_url, json_input, binary_output,
162                             JsonParseOptions());
163 }
164 
165 PROTOBUF_EXPORT util::Status JsonToBinaryString(
166     TypeResolver* resolver, const std::string& type_url,
167     StringPiece json_input, std::string* binary_output,
168     const JsonParseOptions& options);
169 
JsonToBinaryString(TypeResolver * resolver,const std::string & type_url,StringPiece json_input,std::string * binary_output)170 inline util::Status JsonToBinaryString(TypeResolver* resolver,
171                                          const std::string& type_url,
172                                          StringPiece json_input,
173                                          std::string* binary_output) {
174   return JsonToBinaryString(resolver, type_url, json_input, binary_output,
175                             JsonParseOptions());
176 }
177 
178 namespace internal {
179 // Internal helper class. Put in the header so we can write unit-tests for it.
180 class PROTOBUF_EXPORT ZeroCopyStreamByteSink : public strings::ByteSink {
181  public:
ZeroCopyStreamByteSink(io::ZeroCopyOutputStream * stream)182   explicit ZeroCopyStreamByteSink(io::ZeroCopyOutputStream* stream)
183       : stream_(stream), buffer_(NULL), buffer_size_(0) {}
184   ~ZeroCopyStreamByteSink();
185 
186   void Append(const char* bytes, size_t len) override;
187 
188  private:
189   io::ZeroCopyOutputStream* stream_;
190   void* buffer_;
191   int buffer_size_;
192 
193   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyStreamByteSink);
194 };
195 }  // namespace internal
196 
197 }  // namespace util
198 }  // namespace protobuf
199 }  // namespace google
200 
201 #include <google/protobuf/port_undef.inc>
202 
203 #endif  // GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__
204