writer.h 12 KB

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