You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

368 lines
12 KiB

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