writer.h 12 KB

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