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 #ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__ 32 #define GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__ 33 34 #include <memory> 35 #include <string> 36 37 #include <google/protobuf/io/coded_stream.h> 38 #include <google/protobuf/util/internal/structured_objectwriter.h> 39 #include <google/protobuf/stubs/bytestream.h> 40 41 #include <google/protobuf/port_def.inc> 42 43 namespace google { 44 namespace protobuf { 45 namespace util { 46 namespace converter { 47 48 49 // An ObjectWriter implementation that outputs JSON. This ObjectWriter 50 // supports writing a compact form or a pretty printed form. 51 // 52 // Sample usage: 53 // string output; 54 // StringOutputStream* str_stream = new StringOutputStream(&output); 55 // CodedOutputStream* out_stream = new CodedOutputStream(str_stream); 56 // JsonObjectWriter* ow = new JsonObjectWriter(" ", out_stream); 57 // ow->StartObject("") 58 // ->RenderString("name", "value") 59 // ->RenderString("emptystring", string()) 60 // ->StartObject("nested") 61 // ->RenderInt64("light", 299792458); 62 // ->RenderDouble("pi", 3.141592653589793); 63 // ->EndObject() 64 // ->StartList("empty") 65 // ->EndList() 66 // ->EndObject(); 67 // 68 // And then the output string would become: 69 // { 70 // "name": "value", 71 // "emptystring": "", 72 // "nested": { 73 // "light": "299792458", 74 // "pi": 3.141592653589793 75 // }, 76 // "empty": [] 77 // } 78 // 79 // JsonObjectWriter does not validate if calls actually result in valid JSON. 80 // For example, passing an empty name when one would be required won't result 81 // in an error, just an invalid output. 82 // 83 // Note that all int64 and uint64 are rendered as strings instead of numbers. 84 // This is because JavaScript parses numbers as 64-bit float thus int64 and 85 // uint64 would lose precision if rendered as numbers. 86 // 87 // JsonObjectWriter is thread-unsafe. 88 class PROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter { 89 public: JsonObjectWriter(StringPiece indent_string,io::CodedOutputStream * out)90 JsonObjectWriter(StringPiece indent_string, io::CodedOutputStream* out) 91 : element_(new Element(/*parent=*/nullptr, /*is_json_object=*/false)), 92 stream_(out), 93 sink_(out), 94 indent_string_(indent_string), 95 use_websafe_base64_for_bytes_(false) {} 96 virtual ~JsonObjectWriter(); 97 98 // ObjectWriter methods. 99 virtual JsonObjectWriter* StartObject(StringPiece name); 100 virtual JsonObjectWriter* EndObject(); 101 virtual JsonObjectWriter* StartList(StringPiece name); 102 virtual JsonObjectWriter* EndList(); 103 virtual JsonObjectWriter* RenderBool(StringPiece name, bool value); 104 virtual JsonObjectWriter* RenderInt32(StringPiece name, int32 value); 105 virtual JsonObjectWriter* RenderUint32(StringPiece name, uint32 value); 106 virtual JsonObjectWriter* RenderInt64(StringPiece name, int64 value); 107 virtual JsonObjectWriter* RenderUint64(StringPiece name, uint64 value); 108 virtual JsonObjectWriter* RenderDouble(StringPiece name, double value); 109 virtual JsonObjectWriter* RenderFloat(StringPiece name, float value); 110 virtual JsonObjectWriter* RenderString(StringPiece name, 111 StringPiece value); 112 virtual JsonObjectWriter* RenderBytes(StringPiece name, StringPiece value); 113 virtual JsonObjectWriter* RenderNull(StringPiece name); 114 virtual JsonObjectWriter* RenderNullAsEmpty(StringPiece name); 115 set_use_websafe_base64_for_bytes(bool value)116 void set_use_websafe_base64_for_bytes(bool value) { 117 use_websafe_base64_for_bytes_ = value; 118 } 119 120 protected: 121 class PROTOBUF_EXPORT Element : public BaseElement { 122 public: Element(Element * parent,bool is_json_object)123 Element(Element* parent, bool is_json_object) 124 : BaseElement(parent), 125 is_first_(true), 126 is_json_object_(is_json_object) {} 127 128 // Called before each field of the Element is to be processed. 129 // Returns true if this is the first call (processing the first field). is_first()130 bool is_first() { 131 if (is_first_) { 132 is_first_ = false; 133 return true; 134 } 135 return false; 136 } 137 138 // Whether we are currently renderring inside a JSON object (i.e., between 139 // StartObject() and EndObject()). is_json_object()140 bool is_json_object() const { return is_json_object_; } 141 142 private: 143 bool is_first_; 144 bool is_json_object_; 145 146 GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(Element); 147 }; 148 element()149 Element* element() override { return element_.get(); } 150 151 private: 152 class PROTOBUF_EXPORT ByteSinkWrapper : public strings::ByteSink { 153 public: ByteSinkWrapper(io::CodedOutputStream * stream)154 explicit ByteSinkWrapper(io::CodedOutputStream* stream) : stream_(stream) {} ~ByteSinkWrapper()155 ~ByteSinkWrapper() override {} 156 157 // ByteSink methods. Append(const char * bytes,size_t n)158 void Append(const char* bytes, size_t n) override { 159 stream_->WriteRaw(bytes, n); 160 } 161 162 private: 163 io::CodedOutputStream* stream_; 164 165 GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSinkWrapper); 166 }; 167 168 // Renders a simple value as a string. By default all non-string Render 169 // methods convert their argument to a string and call this method. This 170 // method can then be used to render the simple value without escaping it. RenderSimple(StringPiece name,const std::string & value)171 JsonObjectWriter* RenderSimple(StringPiece name, 172 const std::string& value) { 173 WritePrefix(name); 174 stream_->WriteString(value); 175 return this; 176 } 177 178 // Pushes a new JSON array element to the stack. PushArray()179 void PushArray() { 180 element_.reset(new Element(element_.release(), /*is_json_object=*/false)); 181 } 182 183 // Pushes a new JSON object element to the stack. PushObject()184 void PushObject() { 185 element_.reset(new Element(element_.release(), /*is_json_object=*/true)); 186 } 187 188 // Pops an element off of the stack and deletes the popped element. Pop()189 void Pop() { 190 bool needs_newline = !element_->is_first(); 191 element_.reset(element_->pop<Element>()); 192 if (needs_newline) NewLine(); 193 } 194 195 // If pretty printing is enabled, this will write a newline to the output, 196 // followed by optional indentation. Otherwise this method is a noop. NewLine()197 void NewLine() { 198 if (!indent_string_.empty()) { 199 WriteChar('\n'); 200 for (int i = 0; i < element()->level(); i++) { 201 stream_->WriteString(indent_string_); 202 } 203 } 204 } 205 206 // Writes a prefix. This will write out any pretty printing and 207 // commas that are required, followed by the name and a ':' if 208 // the name is not null. 209 void WritePrefix(StringPiece name); 210 211 // Writes an individual character to the output. WriteChar(const char c)212 void WriteChar(const char c) { stream_->WriteRaw(&c, sizeof(c)); } 213 214 std::unique_ptr<Element> element_; 215 io::CodedOutputStream* stream_; 216 ByteSinkWrapper sink_; 217 const std::string indent_string_; 218 219 // Whether to use regular or websafe base64 encoding for byte fields. Defaults 220 // to regular base64 encoding. 221 bool use_websafe_base64_for_bytes_; 222 223 GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(JsonObjectWriter); 224 }; 225 226 } // namespace converter 227 } // namespace util 228 } // namespace protobuf 229 } // namespace google 230 231 #include <google/protobuf/port_undef.inc> 232 233 #endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__ 234