writer.h 12 KB

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