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