writer.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 : public Writer {
  155. public:
  156. FastWriter();
  157. ~FastWriter() override = default;
  158. void enableYAMLCompatibility();
  159. /** \brief Drop the "null" string from the writer's output for nullValues.
  160. * Strictly speaking, this is not valid JSON. But when the output is being
  161. * fed to a browser's JavaScript, it makes for smaller output and the
  162. * browser can handle the output just fine.
  163. */
  164. void dropNullPlaceholders();
  165. void omitEndingLineFeed();
  166. public: // overridden from Writer
  167. String write(const Value& root) override;
  168. private:
  169. void writeValue(const Value& value);
  170. String document_;
  171. bool yamlCompatibilityEnabled_{false};
  172. bool dropNullPlaceholders_{false};
  173. bool omitEndingLineFeed_{false};
  174. };
  175. #if defined(_MSC_VER)
  176. #pragma warning(pop)
  177. #endif
  178. /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
  179. *human friendly way.
  180. *
  181. * The rules for line break and indent are as follow:
  182. * - Object value:
  183. * - if empty then print {} without indent and line break
  184. * - if not empty the print '{', line break & indent, print one value per
  185. *line
  186. * and then unindent and line break and print '}'.
  187. * - Array value:
  188. * - if empty then print [] without indent and line break
  189. * - if the array contains no object value, empty array or some other value
  190. *types,
  191. * and all the values fit on one lines, then print the array on a single
  192. *line.
  193. * - otherwise, it the values do not fit on one line, or the array contains
  194. * object or non empty array, then print one value per line.
  195. *
  196. * If the Value have comments then they are outputted according to their
  197. *#CommentPlacement.
  198. *
  199. * \sa Reader, Value, Value::setComment()
  200. * deprecated Use StreamWriterBuilder.
  201. */
  202. #if defined(_MSC_VER)
  203. #pragma warning(push)
  204. #pragma warning(disable : 4996) // Deriving from deprecated class
  205. #endif
  206. class JSON_API StyledWriter : public Writer {
  207. public:
  208. StyledWriter();
  209. ~StyledWriter() override = default;
  210. public: // overridden from Writer
  211. /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
  212. * \param root Value to serialize.
  213. * \return String containing the JSON document that represents the root value.
  214. */
  215. String write(const Value& root) override;
  216. private:
  217. void writeValue(const Value& value);
  218. void writeArrayValue(const Value& value);
  219. bool isMultilineArray(const Value& value);
  220. void pushValue(const String& value);
  221. void writeIndent();
  222. void writeWithIndent(const String& value);
  223. void indent();
  224. void unindent();
  225. void writeCommentBeforeValue(const Value& root);
  226. void writeCommentAfterValueOnSameLine(const Value& root);
  227. static bool hasCommentForValue(const Value& value);
  228. static String normalizeEOL(const String& text);
  229. using ChildValues = std::vector<String>;
  230. ChildValues childValues_;
  231. String document_;
  232. String indentString_;
  233. unsigned int rightMargin_{74};
  234. unsigned int indentSize_{3};
  235. bool addChildValues_{false};
  236. };
  237. #if defined(_MSC_VER)
  238. #pragma warning(pop)
  239. #endif
  240. /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
  241. human friendly way,
  242. to a stream rather than to a string.
  243. *
  244. * The rules for line break and indent are as follow:
  245. * - Object value:
  246. * - if empty then print {} without indent and line break
  247. * - if not empty the print '{', line break & indent, print one value per
  248. line
  249. * and then unindent and line break and print '}'.
  250. * - Array value:
  251. * - if empty then print [] without indent and line break
  252. * - if the array contains no object value, empty array or some other value
  253. types,
  254. * and all the values fit on one lines, then print the array on a single
  255. line.
  256. * - otherwise, it the values do not fit on one line, or the array contains
  257. * object or non empty array, then print one value per line.
  258. *
  259. * If the Value have comments then they are outputted according to their
  260. #CommentPlacement.
  261. *
  262. * \sa Reader, Value, Value::setComment()
  263. * deprecated Use StreamWriterBuilder.
  264. */
  265. #if defined(_MSC_VER)
  266. #pragma warning(push)
  267. #pragma warning(disable : 4996) // Deriving from deprecated class
  268. #endif
  269. class JSON_API 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. String JSON_API valueToQuotedString(const char* value, size_t length);
  321. /// \brief Output using the StyledStreamWriter.
  322. /// \see Json::operator>>()
  323. JSON_API OStream& operator<<(OStream&, const Value& root);
  324. } // namespace Json
  325. #if !defined(__SUNPRO_CC)
  326. #pragma pack(pop)
  327. #endif
  328. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  329. #pragma warning(pop)
  330. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  331. #endif // JSON_WRITER_H_INCLUDED