1 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 2 // Distributed under MIT license, or public domain if desired and 3 // recognized in your jurisdiction. 4 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 5 6 #ifndef JSON_WRITER_H_INCLUDED 7 #define JSON_WRITER_H_INCLUDED 8 9 #if !defined(JSON_IS_AMALGAMATION) 10 #include "value.h" 11 #endif // if !defined(JSON_IS_AMALGAMATION) 12 #include <vector> 13 #include <string> 14 #include <ostream> 15 16 // Disable warning C4251: <data member>: <type> needs to have dll-interface to 17 // be used by... 18 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER) 19 #pragma warning(push) 20 #pragma warning(disable : 4251) 21 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 22 23 #pragma pack(push, 8) 24 25 namespace Json { 26 27 class Value; 28 29 /** 30 31 Usage: 32 \code 33 using namespace Json; 34 void writeToStdout(StreamWriter::Factory const& factory, Value const& value) { 35 std::unique_ptr<StreamWriter> const writer( 36 factory.newStreamWriter()); 37 writer->write(value, &std::cout); 38 std::cout << std::endl; // add lf and flush 39 } 40 \endcode 41 */ 42 class JSON_API StreamWriter { 43 protected: 44 JSONCPP_OSTREAM* sout_; // not owned; will not delete 45 public: 46 StreamWriter(); 47 virtual ~StreamWriter(); 48 /** Write Value into document as configured in sub-class. 49 Do not take ownership of sout, but maintain a reference during function. 50 \pre sout != NULL 51 \return zero on success (For now, we always return zero, so check the stream instead.) 52 \throw std::exception possibly, depending on configuration 53 */ 54 virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0; 55 56 /** \brief A simple abstract factory. 57 */ 58 class JSON_API Factory { 59 public: 60 virtual ~Factory(); 61 /** \brief Allocate a CharReader via operator new(). 62 * \throw std::exception if something goes wrong (e.g. invalid settings) 63 */ 64 virtual StreamWriter* newStreamWriter() const = 0; 65 }; // Factory 66 }; // StreamWriter 67 68 /** \brief Write into stringstream, then return string, for convenience. 69 * A StreamWriter will be created from the factory, used, and then deleted. 70 */ 71 JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root); 72 73 74 /** \brief Build a StreamWriter implementation. 75 76 Usage: 77 \code 78 using namespace Json; 79 Value value = ...; 80 StreamWriterBuilder builder; 81 builder["commentStyle"] = "None"; 82 builder["indentation"] = " "; // or whatever you like 83 std::unique_ptr<Json::StreamWriter> writer( 84 builder.newStreamWriter()); 85 writer->write(value, &std::cout); 86 std::cout << std::endl; // add lf and flush 87 \endcode 88 */ 89 class JSON_API StreamWriterBuilder : public StreamWriter::Factory { 90 public: 91 // Note: We use a Json::Value so that we can add data-members to this class 92 // without a major version bump. 93 /** Configuration of this builder. 94 Available settings (case-sensitive): 95 - "commentStyle": "None" or "All" 96 - "indentation": "<anything>" 97 - "enableYAMLCompatibility": false or true 98 - slightly change the whitespace around colons 99 - "dropNullPlaceholders": false or true 100 - Drop the "null" string from the writer's output for nullValues. 101 Strictly speaking, this is not valid JSON. But when the output is being 102 fed to a browser's JavaScript, it makes for smaller output and the 103 browser can handle the output just fine. 104 - "useSpecialFloats": false or true 105 - If true, outputs non-finite floating point values in the following way: 106 NaN values as "NaN", positive infinity as "Infinity", and negative infinity 107 as "-Infinity". 108 109 You can examine 'settings_` yourself 110 to see the defaults. You can also write and read them just like any 111 JSON Value. 112 \sa setDefaults() 113 */ 114 Json::Value settings_; 115 116 StreamWriterBuilder(); 117 ~StreamWriterBuilder() JSONCPP_OVERRIDE; 118 119 /** 120 * \throw std::exception if something goes wrong (e.g. invalid settings) 121 */ 122 StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE; 123 124 /** \return true if 'settings' are legal and consistent; 125 * otherwise, indicate bad settings via 'invalid'. 126 */ 127 bool validate(Json::Value* invalid) const; 128 /** A simple way to update a specific setting. 129 */ 130 Value& operator[](JSONCPP_STRING key); 131 132 /** Called by ctor, but you can use this to reset settings_. 133 * \pre 'settings' != NULL (but Json::null is fine) 134 * \remark Defaults: 135 * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults 136 */ 137 static void setDefaults(Json::Value* settings); 138 }; 139 140 /** \brief Abstract class for writers. 141 * \deprecated Use StreamWriter. (And really, this is an implementation detail.) 142 */ 143 class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer { 144 public: 145 virtual ~Writer(); 146 147 virtual JSONCPP_STRING write(const Value& root) = 0; 148 }; 149 150 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format 151 *without formatting (not human friendly). 152 * 153 * The JSON document is written in a single line. It is not intended for 'human' 154 *consumption, 155 * but may be usefull to support feature such as RPC where bandwith is limited. 156 * \sa Reader, Value 157 * \deprecated Use StreamWriterBuilder. 158 */ 159 #if defined(_MSC_VER) 160 #pragma warning(push) 161 #pragma warning(disable:4996) // Deriving from deprecated class 162 #endif 163 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter : public Writer { 164 public: 165 FastWriter(); ~FastWriter()166 ~FastWriter() JSONCPP_OVERRIDE {} 167 168 void enableYAMLCompatibility(); 169 170 /** \brief Drop the "null" string from the writer's output for nullValues. 171 * Strictly speaking, this is not valid JSON. But when the output is being 172 * fed to a browser's JavaScript, it makes for smaller output and the 173 * browser can handle the output just fine. 174 */ 175 void dropNullPlaceholders(); 176 177 void omitEndingLineFeed(); 178 179 public: // overridden from Writer 180 JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; 181 182 private: 183 void writeValue(const Value& value); 184 185 JSONCPP_STRING document_; 186 bool yamlCompatibilityEnabled_; 187 bool dropNullPlaceholders_; 188 bool omitEndingLineFeed_; 189 }; 190 #if defined(_MSC_VER) 191 #pragma warning(pop) 192 #endif 193 194 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a 195 *human friendly way. 196 * 197 * The rules for line break and indent are as follow: 198 * - Object value: 199 * - if empty then print {} without indent and line break 200 * - if not empty the print '{', line break & indent, print one value per 201 *line 202 * and then unindent and line break and print '}'. 203 * - Array value: 204 * - if empty then print [] without indent and line break 205 * - if the array contains no object value, empty array or some other value 206 *types, 207 * and all the values fit on one lines, then print the array on a single 208 *line. 209 * - otherwise, it the values do not fit on one line, or the array contains 210 * object or non empty array, then print one value per line. 211 * 212 * If the Value have comments then they are outputed according to their 213 *#CommentPlacement. 214 * 215 * \sa Reader, Value, Value::setComment() 216 * \deprecated Use StreamWriterBuilder. 217 */ 218 #if defined(_MSC_VER) 219 #pragma warning(push) 220 #pragma warning(disable:4996) // Deriving from deprecated class 221 #endif 222 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter : public Writer { 223 public: 224 StyledWriter(); ~StyledWriter()225 ~StyledWriter() JSONCPP_OVERRIDE {} 226 227 public: // overridden from Writer 228 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format. 229 * \param root Value to serialize. 230 * \return String containing the JSON document that represents the root value. 231 */ 232 JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; 233 234 private: 235 void writeValue(const Value& value); 236 void writeArrayValue(const Value& value); 237 bool isMultilineArray(const Value& value); 238 void pushValue(const JSONCPP_STRING& value); 239 void writeIndent(); 240 void writeWithIndent(const JSONCPP_STRING& value); 241 void indent(); 242 void unindent(); 243 void writeCommentBeforeValue(const Value& root); 244 void writeCommentAfterValueOnSameLine(const Value& root); 245 bool hasCommentForValue(const Value& value); 246 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); 247 248 typedef std::vector<JSONCPP_STRING> ChildValues; 249 250 ChildValues childValues_; 251 JSONCPP_STRING document_; 252 JSONCPP_STRING indentString_; 253 unsigned int rightMargin_; 254 unsigned int indentSize_; 255 bool addChildValues_; 256 }; 257 #if defined(_MSC_VER) 258 #pragma warning(pop) 259 #endif 260 261 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a 262 human friendly way, 263 to a stream rather than to a string. 264 * 265 * The rules for line break and indent are as follow: 266 * - Object value: 267 * - if empty then print {} without indent and line break 268 * - if not empty the print '{', line break & indent, print one value per 269 line 270 * and then unindent and line break and print '}'. 271 * - Array value: 272 * - if empty then print [] without indent and line break 273 * - if the array contains no object value, empty array or some other value 274 types, 275 * and all the values fit on one lines, then print the array on a single 276 line. 277 * - otherwise, it the values do not fit on one line, or the array contains 278 * object or non empty array, then print one value per line. 279 * 280 * If the Value have comments then they are outputed according to their 281 #CommentPlacement. 282 * 283 * \sa Reader, Value, Value::setComment() 284 * \deprecated Use StreamWriterBuilder. 285 */ 286 #if defined(_MSC_VER) 287 #pragma warning(push) 288 #pragma warning(disable:4996) // Deriving from deprecated class 289 #endif 290 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter { 291 public: 292 /** 293 * \param indentation Each level will be indented by this amount extra. 294 */ 295 StyledStreamWriter(JSONCPP_STRING indentation = "\t"); ~StyledStreamWriter()296 ~StyledStreamWriter() {} 297 298 public: 299 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format. 300 * \param out Stream to write to. (Can be ostringstream, e.g.) 301 * \param root Value to serialize. 302 * \note There is no point in deriving from Writer, since write() should not 303 * return a value. 304 */ 305 void write(JSONCPP_OSTREAM& out, const Value& root); 306 307 private: 308 void writeValue(const Value& value); 309 void writeArrayValue(const Value& value); 310 bool isMultilineArray(const Value& value); 311 void pushValue(const JSONCPP_STRING& value); 312 void writeIndent(); 313 void writeWithIndent(const JSONCPP_STRING& value); 314 void indent(); 315 void unindent(); 316 void writeCommentBeforeValue(const Value& root); 317 void writeCommentAfterValueOnSameLine(const Value& root); 318 bool hasCommentForValue(const Value& value); 319 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); 320 321 typedef std::vector<JSONCPP_STRING> ChildValues; 322 323 ChildValues childValues_; 324 JSONCPP_OSTREAM* document_; 325 JSONCPP_STRING indentString_; 326 unsigned int rightMargin_; 327 JSONCPP_STRING indentation_; 328 bool addChildValues_ : 1; 329 bool indented_ : 1; 330 }; 331 #if defined(_MSC_VER) 332 #pragma warning(pop) 333 #endif 334 335 #if defined(JSON_HAS_INT64) 336 JSONCPP_STRING JSON_API valueToString(Int value); 337 JSONCPP_STRING JSON_API valueToString(UInt value); 338 #endif // if defined(JSON_HAS_INT64) 339 JSONCPP_STRING JSON_API valueToString(LargestInt value); 340 JSONCPP_STRING JSON_API valueToString(LargestUInt value); 341 JSONCPP_STRING JSON_API valueToString(double value); 342 JSONCPP_STRING JSON_API valueToString(bool value); 343 JSONCPP_STRING JSON_API valueToQuotedString(const char* value); 344 345 /// \brief Output using the StyledStreamWriter. 346 /// \see Json::operator>>() 347 JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root); 348 349 } // namespace Json 350 351 #pragma pack(pop) 352 353 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 354 #pragma warning(pop) 355 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 356 357 #endif // JSON_WRITER_H_INCLUDED 358