json.h 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  1. /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
  2. /// It is intended to be used with #include "json/json.h"
  3. // //////////////////////////////////////////////////////////////////////
  4. // Beginning of content of file: LICENSE
  5. // //////////////////////////////////////////////////////////////////////
  6. /*
  7. The JsonCpp library's source code, including accompanying documentation,
  8. tests and demonstration applications, are licensed under the following
  9. conditions...
  10. The author (Baptiste Lepilleur) explicitly disclaims copyright in all
  11. jurisdictions which recognize such a disclaimer. In such jurisdictions,
  12. this software is released into the Public Domain.
  13. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
  14. 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
  15. released under the terms of the MIT License (see below).
  16. In jurisdictions which recognize Public Domain property, the user of this
  17. software may choose to accept it either as 1) Public Domain, 2) under the
  18. conditions of the MIT License (see below), or 3) under the terms of dual
  19. Public Domain/MIT License conditions described here, as they choose.
  20. The MIT License is about as close to Public Domain as a license can get, and is
  21. described in clear, concise terms at:
  22. http://en.wikipedia.org/wiki/MIT_License
  23. The full text of the MIT License follows:
  24. ========================================================================
  25. Copyright (c) 2007-2010 Baptiste Lepilleur
  26. Permission is hereby granted, free of charge, to any person
  27. obtaining a copy of this software and associated documentation
  28. files (the "Software"), to deal in the Software without
  29. restriction, including without limitation the rights to use, copy,
  30. modify, merge, publish, distribute, sublicense, and/or sell copies
  31. of the Software, and to permit persons to whom the Software is
  32. furnished to do so, subject to the following conditions:
  33. The above copyright notice and this permission notice shall be
  34. included in all copies or substantial portions of the Software.
  35. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  36. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  37. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  38. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  39. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  40. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  41. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  42. SOFTWARE.
  43. ========================================================================
  44. (END LICENSE TEXT)
  45. The MIT license is compatible with both the GPL and commercial
  46. software, affording one all of the rights of Public Domain with the
  47. minor nuisance of being required to keep the above copyright notice
  48. and license text in the source code. Note also that by accepting the
  49. Public Domain "license" you can re-license your copy using whatever
  50. license you like.
  51. */
  52. // //////////////////////////////////////////////////////////////////////
  53. // End of content of file: LICENSE
  54. // //////////////////////////////////////////////////////////////////////
  55. #ifndef JSON_AMALGATED_H_INCLUDED
  56. # define JSON_AMALGATED_H_INCLUDED
  57. /// If defined, indicates that the source file is amalgated
  58. /// to prevent private header inclusion.
  59. #define JSON_IS_AMALGAMATION
  60. // //////////////////////////////////////////////////////////////////////
  61. // Beginning of content of file: include/json/version.h
  62. // //////////////////////////////////////////////////////////////////////
  63. // DO NOT EDIT. This file (and "version") is generated by CMake.
  64. // Run CMake configure step to update it.
  65. #ifndef JSON_VERSION_H_INCLUDED
  66. # define JSON_VERSION_H_INCLUDED
  67. # define JSONCPP_VERSION_STRING "1.6.5"
  68. # define JSONCPP_VERSION_MAJOR 1
  69. # define JSONCPP_VERSION_MINOR 6
  70. # define JSONCPP_VERSION_PATCH 5
  71. # define JSONCPP_VERSION_QUALIFIER
  72. # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
  73. #endif // JSON_VERSION_H_INCLUDED
  74. // //////////////////////////////////////////////////////////////////////
  75. // End of content of file: include/json/version.h
  76. // //////////////////////////////////////////////////////////////////////
  77. // //////////////////////////////////////////////////////////////////////
  78. // Beginning of content of file: include/json/config.h
  79. // //////////////////////////////////////////////////////////////////////
  80. // Copyright 2007-2010 Baptiste Lepilleur
  81. // Distributed under MIT license, or public domain if desired and
  82. // recognized in your jurisdiction.
  83. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  84. #ifndef JSON_CONFIG_H_INCLUDED
  85. #define JSON_CONFIG_H_INCLUDED
  86. /// If defined, indicates that json library is embedded in CppTL library.
  87. //# define JSON_IN_CPPTL 1
  88. /// If defined, indicates that json may leverage CppTL library
  89. //# define JSON_USE_CPPTL 1
  90. /// If defined, indicates that cpptl vector based map should be used instead of
  91. /// std::map
  92. /// as Value container.
  93. //# define JSON_USE_CPPTL_SMALLMAP 1
  94. // If non-zero, the library uses exceptions to report bad input instead of C
  95. // assertion macros. The default is to use exceptions.
  96. #ifndef JSON_USE_EXCEPTION
  97. #define JSON_USE_EXCEPTION 1
  98. #endif
  99. /// If defined, indicates that the source file is amalgated
  100. /// to prevent private header inclusion.
  101. /// Remarks: it is automatically defined in the generated amalgated header.
  102. // #define JSON_IS_AMALGAMATION
  103. #ifdef JSON_IN_CPPTL
  104. #include <cpptl/config.h>
  105. #ifndef JSON_USE_CPPTL
  106. #define JSON_USE_CPPTL 1
  107. #endif
  108. #endif
  109. #ifdef JSON_IN_CPPTL
  110. #define JSON_API CPPTL_API
  111. #elif defined(JSON_DLL_BUILD)
  112. #if defined(_MSC_VER)
  113. #define JSON_API __declspec(dllexport)
  114. #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
  115. #endif // if defined(_MSC_VER)
  116. #elif defined(JSON_DLL)
  117. #if defined(_MSC_VER)
  118. #define JSON_API __declspec(dllimport)
  119. #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
  120. #endif // if defined(_MSC_VER)
  121. #endif // ifdef JSON_IN_CPPTL
  122. #if !defined(JSON_API)
  123. #define JSON_API
  124. #endif
  125. // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
  126. // integer
  127. // Storages, and 64 bits integer support is disabled.
  128. // #define JSON_NO_INT64 1
  129. #if defined(_MSC_VER) // MSVC
  130. # if _MSC_VER <= 1200 // MSVC 6
  131. // Microsoft Visual Studio 6 only support conversion from __int64 to double
  132. // (no conversion from unsigned __int64).
  133. # define JSON_USE_INT64_DOUBLE_CONVERSION 1
  134. // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
  135. // characters in the debug information)
  136. // All projects I've ever seen with VS6 were using this globally (not bothering
  137. // with pragma push/pop).
  138. # pragma warning(disable : 4786)
  139. # endif // MSVC 6
  140. # if _MSC_VER >= 1500 // MSVC 2008
  141. /// Indicates that the following function is deprecated.
  142. # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
  143. # endif
  144. #endif // defined(_MSC_VER)
  145. #ifndef JSON_HAS_RVALUE_REFERENCES
  146. #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
  147. #define JSON_HAS_RVALUE_REFERENCES 1
  148. #endif // MSVC >= 2010
  149. #ifdef __clang__
  150. #if __has_feature(cxx_rvalue_references)
  151. #define JSON_HAS_RVALUE_REFERENCES 1
  152. #endif // has_feature
  153. #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
  154. #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
  155. #define JSON_HAS_RVALUE_REFERENCES 1
  156. #endif // GXX_EXPERIMENTAL
  157. #endif // __clang__ || __GNUC__
  158. #endif // not defined JSON_HAS_RVALUE_REFERENCES
  159. #ifndef JSON_HAS_RVALUE_REFERENCES
  160. #define JSON_HAS_RVALUE_REFERENCES 0
  161. #endif
  162. #ifdef __clang__
  163. #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
  164. # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
  165. # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
  166. # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
  167. # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
  168. # endif // GNUC version
  169. #endif // __clang__ || __GNUC__
  170. #if !defined(JSONCPP_DEPRECATED)
  171. #define JSONCPP_DEPRECATED(message)
  172. #endif // if !defined(JSONCPP_DEPRECATED)
  173. namespace Json {
  174. typedef int Int;
  175. typedef unsigned int UInt;
  176. #if defined(JSON_NO_INT64)
  177. typedef int LargestInt;
  178. typedef unsigned int LargestUInt;
  179. #undef JSON_HAS_INT64
  180. #else // if defined(JSON_NO_INT64)
  181. // For Microsoft Visual use specific types as long long is not supported
  182. #if defined(_MSC_VER) // Microsoft Visual Studio
  183. typedef __int64 Int64;
  184. typedef unsigned __int64 UInt64;
  185. #else // if defined(_MSC_VER) // Other platforms, use long long
  186. typedef long long int Int64;
  187. typedef unsigned long long int UInt64;
  188. #endif // if defined(_MSC_VER)
  189. typedef Int64 LargestInt;
  190. typedef UInt64 LargestUInt;
  191. #define JSON_HAS_INT64
  192. #endif // if defined(JSON_NO_INT64)
  193. } // end namespace Json
  194. #endif // JSON_CONFIG_H_INCLUDED
  195. // //////////////////////////////////////////////////////////////////////
  196. // End of content of file: include/json/config.h
  197. // //////////////////////////////////////////////////////////////////////
  198. // //////////////////////////////////////////////////////////////////////
  199. // Beginning of content of file: include/json/forwards.h
  200. // //////////////////////////////////////////////////////////////////////
  201. // Copyright 2007-2010 Baptiste Lepilleur
  202. // Distributed under MIT license, or public domain if desired and
  203. // recognized in your jurisdiction.
  204. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  205. #ifndef JSON_FORWARDS_H_INCLUDED
  206. #define JSON_FORWARDS_H_INCLUDED
  207. #if !defined(JSON_IS_AMALGAMATION)
  208. #include "config.h"
  209. #endif // if !defined(JSON_IS_AMALGAMATION)
  210. namespace Json {
  211. // writer.h
  212. class FastWriter;
  213. class StyledWriter;
  214. // reader.h
  215. class Reader;
  216. // features.h
  217. class Features;
  218. // value.h
  219. typedef unsigned int ArrayIndex;
  220. class StaticString;
  221. class Path;
  222. class PathArgument;
  223. class Value;
  224. class ValueIteratorBase;
  225. class ValueIterator;
  226. class ValueConstIterator;
  227. } // namespace Json
  228. #endif // JSON_FORWARDS_H_INCLUDED
  229. // //////////////////////////////////////////////////////////////////////
  230. // End of content of file: include/json/forwards.h
  231. // //////////////////////////////////////////////////////////////////////
  232. // //////////////////////////////////////////////////////////////////////
  233. // Beginning of content of file: include/json/features.h
  234. // //////////////////////////////////////////////////////////////////////
  235. // Copyright 2007-2010 Baptiste Lepilleur
  236. // Distributed under MIT license, or public domain if desired and
  237. // recognized in your jurisdiction.
  238. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  239. #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
  240. #define CPPTL_JSON_FEATURES_H_INCLUDED
  241. #if !defined(JSON_IS_AMALGAMATION)
  242. #include "forwards.h"
  243. #endif // if !defined(JSON_IS_AMALGAMATION)
  244. namespace Json {
  245. /** \brief Configuration passed to reader and writer.
  246. * This configuration object can be used to force the Reader or Writer
  247. * to behave in a standard conforming way.
  248. */
  249. class JSON_API Features {
  250. public:
  251. /** \brief A configuration that allows all features and assumes all strings
  252. * are UTF-8.
  253. * - C & C++ comments are allowed
  254. * - Root object can be any JSON value
  255. * - Assumes Value strings are encoded in UTF-8
  256. */
  257. static Features all();
  258. /** \brief A configuration that is strictly compatible with the JSON
  259. * specification.
  260. * - Comments are forbidden.
  261. * - Root object must be either an array or an object value.
  262. * - Assumes Value strings are encoded in UTF-8
  263. */
  264. static Features strictMode();
  265. /** \brief Initialize the configuration like JsonConfig::allFeatures;
  266. */
  267. Features();
  268. /// \c true if comments are allowed. Default: \c true.
  269. bool allowComments_;
  270. /// \c true if root must be either an array or an object value. Default: \c
  271. /// false.
  272. bool strictRoot_;
  273. /// \c true if dropped null placeholders are allowed. Default: \c false.
  274. bool allowDroppedNullPlaceholders_;
  275. /// \c true if numeric object key are allowed. Default: \c false.
  276. bool allowNumericKeys_;
  277. };
  278. } // namespace Json
  279. #endif // CPPTL_JSON_FEATURES_H_INCLUDED
  280. // //////////////////////////////////////////////////////////////////////
  281. // End of content of file: include/json/features.h
  282. // //////////////////////////////////////////////////////////////////////
  283. // //////////////////////////////////////////////////////////////////////
  284. // Beginning of content of file: include/json/value.h
  285. // //////////////////////////////////////////////////////////////////////
  286. // Copyright 2007-2010 Baptiste Lepilleur
  287. // Distributed under MIT license, or public domain if desired and
  288. // recognized in your jurisdiction.
  289. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  290. #ifndef CPPTL_JSON_H_INCLUDED
  291. #define CPPTL_JSON_H_INCLUDED
  292. #if !defined(JSON_IS_AMALGAMATION)
  293. #include "forwards.h"
  294. #endif // if !defined(JSON_IS_AMALGAMATION)
  295. #include <string>
  296. #include <vector>
  297. #include <exception>
  298. #ifndef JSON_USE_CPPTL_SMALLMAP
  299. #include <map>
  300. #else
  301. #include <cpptl/smallmap.h>
  302. #endif
  303. #ifdef JSON_USE_CPPTL
  304. #include <cpptl/forwards.h>
  305. #endif
  306. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  307. // be used by...
  308. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  309. #pragma warning(push)
  310. #pragma warning(disable : 4251)
  311. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  312. /** \brief JSON (JavaScript Object Notation).
  313. */
  314. namespace Json {
  315. /** Base class for all exceptions we throw.
  316. *
  317. * We use nothing but these internally. Of course, STL can throw others.
  318. */
  319. class JSON_API Exception : public std::exception {
  320. public:
  321. Exception(std::string const& msg);
  322. ~Exception() throw() override;
  323. char const* what() const throw() override;
  324. protected:
  325. std::string msg_;
  326. };
  327. /** Exceptions which the user cannot easily avoid.
  328. *
  329. * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
  330. *
  331. * \remark derived from Json::Exception
  332. */
  333. class JSON_API RuntimeError : public Exception {
  334. public:
  335. RuntimeError(std::string const& msg);
  336. };
  337. /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
  338. *
  339. * These are precondition-violations (user bugs) and internal errors (our bugs).
  340. *
  341. * \remark derived from Json::Exception
  342. */
  343. class JSON_API LogicError : public Exception {
  344. public:
  345. LogicError(std::string const& msg);
  346. };
  347. /// used internally
  348. void throwRuntimeError(std::string const& msg);
  349. /// used internally
  350. void throwLogicError(std::string const& msg);
  351. /** \brief Type of the value held by a Value object.
  352. */
  353. enum ValueType {
  354. nullValue = 0, ///< 'null' value
  355. intValue, ///< signed integer value
  356. uintValue, ///< unsigned integer value
  357. realValue, ///< double value
  358. stringValue, ///< UTF-8 string value
  359. booleanValue, ///< bool value
  360. arrayValue, ///< array value (ordered list)
  361. objectValue ///< object value (collection of name/value pairs).
  362. };
  363. enum CommentPlacement {
  364. commentBefore = 0, ///< a comment placed on the line before a value
  365. commentAfterOnSameLine, ///< a comment just after a value on the same line
  366. commentAfter, ///< a comment on the line after a value (only make sense for
  367. /// root value)
  368. numberOfCommentPlacement
  369. };
  370. //# ifdef JSON_USE_CPPTL
  371. // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
  372. // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
  373. //# endif
  374. /** \brief Lightweight wrapper to tag static string.
  375. *
  376. * Value constructor and objectValue member assignement takes advantage of the
  377. * StaticString and avoid the cost of string duplication when storing the
  378. * string or the member name.
  379. *
  380. * Example of usage:
  381. * \code
  382. * Json::Value aValue( StaticString("some text") );
  383. * Json::Value object;
  384. * static const StaticString code("code");
  385. * object[code] = 1234;
  386. * \endcode
  387. */
  388. class JSON_API StaticString {
  389. public:
  390. explicit StaticString(const char* czstring) : c_str_(czstring) {}
  391. operator const char*() const { return c_str_; }
  392. const char* c_str() const { return c_str_; }
  393. private:
  394. const char* c_str_;
  395. };
  396. /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
  397. *
  398. * This class is a discriminated union wrapper that can represents a:
  399. * - signed integer [range: Value::minInt - Value::maxInt]
  400. * - unsigned integer (range: 0 - Value::maxUInt)
  401. * - double
  402. * - UTF-8 string
  403. * - boolean
  404. * - 'null'
  405. * - an ordered list of Value
  406. * - collection of name/value pairs (javascript object)
  407. *
  408. * The type of the held value is represented by a #ValueType and
  409. * can be obtained using type().
  410. *
  411. * Values of an #objectValue or #arrayValue can be accessed using operator[]()
  412. * methods.
  413. * Non-const methods will automatically create the a #nullValue element
  414. * if it does not exist.
  415. * The sequence of an #arrayValue will be automatically resized and initialized
  416. * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
  417. *
  418. * The get() methods can be used to obtain default value in the case the
  419. * required element does not exist.
  420. *
  421. * It is possible to iterate over the list of a #objectValue values using
  422. * the getMemberNames() method.
  423. *
  424. * \note #Value string-length fit in size_t, but keys must be < 2^30.
  425. * (The reason is an implementation detail.) A #CharReader will raise an
  426. * exception if a bound is exceeded to avoid security holes in your app,
  427. * but the Value API does *not* check bounds. That is the responsibility
  428. * of the caller.
  429. */
  430. class JSON_API Value {
  431. friend class ValueIteratorBase;
  432. public:
  433. typedef std::vector<std::string> Members;
  434. typedef ValueIterator iterator;
  435. typedef ValueConstIterator const_iterator;
  436. typedef Json::UInt UInt;
  437. typedef Json::Int Int;
  438. #if defined(JSON_HAS_INT64)
  439. typedef Json::UInt64 UInt64;
  440. typedef Json::Int64 Int64;
  441. #endif // defined(JSON_HAS_INT64)
  442. typedef Json::LargestInt LargestInt;
  443. typedef Json::LargestUInt LargestUInt;
  444. typedef Json::ArrayIndex ArrayIndex;
  445. static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
  446. static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
  447. /// Minimum signed integer value that can be stored in a Json::Value.
  448. static const LargestInt minLargestInt;
  449. /// Maximum signed integer value that can be stored in a Json::Value.
  450. static const LargestInt maxLargestInt;
  451. /// Maximum unsigned integer value that can be stored in a Json::Value.
  452. static const LargestUInt maxLargestUInt;
  453. /// Minimum signed int value that can be stored in a Json::Value.
  454. static const Int minInt;
  455. /// Maximum signed int value that can be stored in a Json::Value.
  456. static const Int maxInt;
  457. /// Maximum unsigned int value that can be stored in a Json::Value.
  458. static const UInt maxUInt;
  459. #if defined(JSON_HAS_INT64)
  460. /// Minimum signed 64 bits int value that can be stored in a Json::Value.
  461. static const Int64 minInt64;
  462. /// Maximum signed 64 bits int value that can be stored in a Json::Value.
  463. static const Int64 maxInt64;
  464. /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
  465. static const UInt64 maxUInt64;
  466. #endif // defined(JSON_HAS_INT64)
  467. private:
  468. #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  469. class CZString {
  470. public:
  471. enum DuplicationPolicy {
  472. noDuplication = 0,
  473. duplicate,
  474. duplicateOnCopy
  475. };
  476. CZString(ArrayIndex index);
  477. CZString(char const* str, unsigned length, DuplicationPolicy allocate);
  478. CZString(CZString const& other);
  479. #if JSON_HAS_RVALUE_REFERENCES
  480. CZString(CZString&& other);
  481. #endif
  482. ~CZString();
  483. CZString& operator=(CZString other);
  484. bool operator<(CZString const& other) const;
  485. bool operator==(CZString const& other) const;
  486. ArrayIndex index() const;
  487. //const char* c_str() const; ///< \deprecated
  488. char const* data() const;
  489. unsigned length() const;
  490. bool isStaticString() const;
  491. private:
  492. void swap(CZString& other);
  493. struct StringStorage {
  494. unsigned policy_: 2;
  495. unsigned length_: 30; // 1GB max
  496. };
  497. char const* cstr_; // actually, a prefixed string, unless policy is noDup
  498. union {
  499. ArrayIndex index_;
  500. StringStorage storage_;
  501. };
  502. };
  503. public:
  504. #ifndef JSON_USE_CPPTL_SMALLMAP
  505. typedef std::map<CZString, Value> ObjectValues;
  506. #else
  507. typedef CppTL::SmallMap<CZString, Value> ObjectValues;
  508. #endif // ifndef JSON_USE_CPPTL_SMALLMAP
  509. #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
  510. public:
  511. /** \brief Create a default Value of the given type.
  512. This is a very useful constructor.
  513. To create an empty array, pass arrayValue.
  514. To create an empty object, pass objectValue.
  515. Another Value can then be set to this one by assignment.
  516. This is useful since clear() and resize() will not alter types.
  517. Examples:
  518. \code
  519. Json::Value null_value; // null
  520. Json::Value arr_value(Json::arrayValue); // []
  521. Json::Value obj_value(Json::objectValue); // {}
  522. \endcode
  523. */
  524. Value(ValueType type = nullValue);
  525. Value(Int value);
  526. Value(UInt value);
  527. #if defined(JSON_HAS_INT64)
  528. Value(Int64 value);
  529. Value(UInt64 value);
  530. #endif // if defined(JSON_HAS_INT64)
  531. Value(double value);
  532. Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
  533. Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
  534. /** \brief Constructs a value from a static string.
  535. * Like other value string constructor but do not duplicate the string for
  536. * internal storage. The given string must remain alive after the call to this
  537. * constructor.
  538. * \note This works only for null-terminated strings. (We cannot change the
  539. * size of this class, so we have nowhere to store the length,
  540. * which might be computed later for various operations.)
  541. *
  542. * Example of usage:
  543. * \code
  544. * static StaticString foo("some text");
  545. * Json::Value aValue(foo);
  546. * \endcode
  547. */
  548. Value(const StaticString& value);
  549. Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too.
  550. #ifdef JSON_USE_CPPTL
  551. Value(const CppTL::ConstString& value);
  552. #endif
  553. Value(bool value);
  554. /// Deep copy.
  555. Value(const Value& other);
  556. #if JSON_HAS_RVALUE_REFERENCES
  557. /// Move constructor
  558. Value(Value&& other);
  559. #endif
  560. ~Value();
  561. /// Deep copy, then swap(other).
  562. /// \note Over-write existing comments. To preserve comments, use #swapPayload().
  563. Value& operator=(Value other);
  564. /// Swap everything.
  565. void swap(Value& other);
  566. /// Swap values but leave comments and source offsets in place.
  567. void swapPayload(Value& other);
  568. ValueType type() const;
  569. /// Compare payload only, not comments etc.
  570. bool operator<(const Value& other) const;
  571. bool operator<=(const Value& other) const;
  572. bool operator>=(const Value& other) const;
  573. bool operator>(const Value& other) const;
  574. bool operator==(const Value& other) const;
  575. bool operator!=(const Value& other) const;
  576. int compare(const Value& other) const;
  577. const char* asCString() const; ///< Embedded zeroes could cause you trouble!
  578. std::string asString() const; ///< Embedded zeroes are possible.
  579. /** Get raw char* of string-value.
  580. * \return false if !string. (Seg-fault if str or end are NULL.)
  581. */
  582. bool getString(
  583. char const** begin, char const** end) const;
  584. #ifdef JSON_USE_CPPTL
  585. CppTL::ConstString asConstString() const;
  586. #endif
  587. Int asInt() const;
  588. UInt asUInt() const;
  589. #if defined(JSON_HAS_INT64)
  590. Int64 asInt64() const;
  591. UInt64 asUInt64() const;
  592. #endif // if defined(JSON_HAS_INT64)
  593. LargestInt asLargestInt() const;
  594. LargestUInt asLargestUInt() const;
  595. float asFloat() const;
  596. double asDouble() const;
  597. bool asBool() const;
  598. bool isNull() const;
  599. bool isBool() const;
  600. bool isInt() const;
  601. bool isInt64() const;
  602. bool isUInt() const;
  603. bool isUInt64() const;
  604. bool isIntegral() const;
  605. bool isDouble() const;
  606. bool isNumeric() const;
  607. bool isString() const;
  608. bool isArray() const;
  609. bool isObject() const;
  610. bool isConvertibleTo(ValueType other) const;
  611. /// Number of values in array or object
  612. ArrayIndex size() const;
  613. /// \brief Return true if empty array, empty object, or null;
  614. /// otherwise, false.
  615. bool empty() const;
  616. /// Return isNull()
  617. bool operator!() const;
  618. /// Remove all object members and array elements.
  619. /// \pre type() is arrayValue, objectValue, or nullValue
  620. /// \post type() is unchanged
  621. void clear();
  622. /// Resize the array to size elements.
  623. /// New elements are initialized to null.
  624. /// May only be called on nullValue or arrayValue.
  625. /// \pre type() is arrayValue or nullValue
  626. /// \post type() is arrayValue
  627. void resize(ArrayIndex size);
  628. /// Access an array element (zero based index ).
  629. /// If the array contains less than index element, then null value are
  630. /// inserted
  631. /// in the array so that its size is index+1.
  632. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  633. /// this from the operator[] which takes a string.)
  634. Value& operator[](ArrayIndex index);
  635. /// Access an array element (zero based index ).
  636. /// If the array contains less than index element, then null value are
  637. /// inserted
  638. /// in the array so that its size is index+1.
  639. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  640. /// this from the operator[] which takes a string.)
  641. Value& operator[](int index);
  642. /// Access an array element (zero based index )
  643. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  644. /// this from the operator[] which takes a string.)
  645. const Value& operator[](ArrayIndex index) const;
  646. /// Access an array element (zero based index )
  647. /// (You may need to say 'value[0u]' to get your compiler to distinguish
  648. /// this from the operator[] which takes a string.)
  649. const Value& operator[](int index) const;
  650. /// If the array contains at least index+1 elements, returns the element
  651. /// value,
  652. /// otherwise returns defaultValue.
  653. Value get(ArrayIndex index, const Value& defaultValue) const;
  654. /// Return true if index < size().
  655. bool isValidIndex(ArrayIndex index) const;
  656. /// \brief Append value to array at the end.
  657. ///
  658. /// Equivalent to jsonvalue[jsonvalue.size()] = value;
  659. Value& append(const Value& value);
  660. /// Access an object value by name, create a null member if it does not exist.
  661. /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
  662. /// Exceeding that will cause an exception.
  663. Value& operator[](const char* key);
  664. /// Access an object value by name, returns null if there is no member with
  665. /// that name.
  666. const Value& operator[](const char* key) const;
  667. /// Access an object value by name, create a null member if it does not exist.
  668. /// \param key may contain embedded nulls.
  669. Value& operator[](const std::string& key);
  670. /// Access an object value by name, returns null if there is no member with
  671. /// that name.
  672. /// \param key may contain embedded nulls.
  673. const Value& operator[](const std::string& key) const;
  674. /** \brief Access an object value by name, create a null member if it does not
  675. exist.
  676. * If the object has no entry for that name, then the member name used to store
  677. * the new entry is not duplicated.
  678. * Example of use:
  679. * \code
  680. * Json::Value object;
  681. * static const StaticString code("code");
  682. * object[code] = 1234;
  683. * \endcode
  684. */
  685. Value& operator[](const StaticString& key);
  686. #ifdef JSON_USE_CPPTL
  687. /// Access an object value by name, create a null member if it does not exist.
  688. Value& operator[](const CppTL::ConstString& key);
  689. /// Access an object value by name, returns null if there is no member with
  690. /// that name.
  691. const Value& operator[](const CppTL::ConstString& key) const;
  692. #endif
  693. /// Return the member named key if it exist, defaultValue otherwise.
  694. /// \note deep copy
  695. Value get(const char* key, const Value& defaultValue) const;
  696. /// Return the member named key if it exist, defaultValue otherwise.
  697. /// \note deep copy
  698. /// \note key may contain embedded nulls.
  699. Value get(const char* begin, const char* end, const Value& defaultValue) const;
  700. /// Return the member named key if it exist, defaultValue otherwise.
  701. /// \note deep copy
  702. /// \param key may contain embedded nulls.
  703. Value get(const std::string& key, const Value& defaultValue) const;
  704. #ifdef JSON_USE_CPPTL
  705. /// Return the member named key if it exist, defaultValue otherwise.
  706. /// \note deep copy
  707. Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
  708. #endif
  709. /// Most general and efficient version of isMember()const, get()const,
  710. /// and operator[]const
  711. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  712. Value const* find(char const* begin, char const* end) const;
  713. /// Most general and efficient version of object-mutators.
  714. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
  715. /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
  716. Value const* demand(char const* begin, char const* end);
  717. /// \brief Remove and return the named member.
  718. ///
  719. /// Do nothing if it did not exist.
  720. /// \return the removed Value, or null.
  721. /// \pre type() is objectValue or nullValue
  722. /// \post type() is unchanged
  723. /// \deprecated
  724. Value removeMember(const char* key);
  725. /// Same as removeMember(const char*)
  726. /// \param key may contain embedded nulls.
  727. /// \deprecated
  728. Value removeMember(const std::string& key);
  729. /// Same as removeMember(const char* begin, const char* end, Value* removed),
  730. /// but 'key' is null-terminated.
  731. bool removeMember(const char* key, Value* removed);
  732. /** \brief Remove the named map member.
  733. Update 'removed' iff removed.
  734. \param key may contain embedded nulls.
  735. \return true iff removed (no exceptions)
  736. */
  737. bool removeMember(std::string const& key, Value* removed);
  738. /// Same as removeMember(std::string const& key, Value* removed)
  739. bool removeMember(const char* begin, const char* end, Value* removed);
  740. /** \brief Remove the indexed array element.
  741. O(n) expensive operations.
  742. Update 'removed' iff removed.
  743. \return true iff removed (no exceptions)
  744. */
  745. bool removeIndex(ArrayIndex i, Value* removed);
  746. /// Return true if the object has a member named key.
  747. /// \note 'key' must be null-terminated.
  748. bool isMember(const char* key) const;
  749. /// Return true if the object has a member named key.
  750. /// \param key may contain embedded nulls.
  751. bool isMember(const std::string& key) const;
  752. /// Same as isMember(std::string const& key)const
  753. bool isMember(const char* begin, const char* end) const;
  754. #ifdef JSON_USE_CPPTL
  755. /// Return true if the object has a member named key.
  756. bool isMember(const CppTL::ConstString& key) const;
  757. #endif
  758. /// \brief Return a list of the member names.
  759. ///
  760. /// If null, return an empty list.
  761. /// \pre type() is objectValue or nullValue
  762. /// \post if type() was nullValue, it remains nullValue
  763. Members getMemberNames() const;
  764. //# ifdef JSON_USE_CPPTL
  765. // EnumMemberNames enumMemberNames() const;
  766. // EnumValues enumValues() const;
  767. //# endif
  768. /// \deprecated Always pass len.
  769. JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.")
  770. void setComment(const char* comment, CommentPlacement placement);
  771. /// Comments must be //... or /* ... */
  772. void setComment(const char* comment, size_t len, CommentPlacement placement);
  773. /// Comments must be //... or /* ... */
  774. void setComment(const std::string& comment, CommentPlacement placement);
  775. bool hasComment(CommentPlacement placement) const;
  776. /// Include delimiters and embedded newlines.
  777. std::string getComment(CommentPlacement placement) const;
  778. std::string toStyledString() const;
  779. const_iterator begin() const;
  780. const_iterator end() const;
  781. iterator begin();
  782. iterator end();
  783. // Accessors for the [start, limit) range of bytes within the JSON text from
  784. // which this value was parsed, if any.
  785. void setOffsetStart(size_t start);
  786. void setOffsetLimit(size_t limit);
  787. size_t getOffsetStart() const;
  788. size_t getOffsetLimit() const;
  789. private:
  790. void initBasic(ValueType type, bool allocated = false);
  791. Value& resolveReference(const char* key);
  792. Value& resolveReference(const char* key, const char* end);
  793. struct CommentInfo {
  794. CommentInfo();
  795. ~CommentInfo();
  796. void setComment(const char* text, size_t len);
  797. char* comment_;
  798. };
  799. // struct MemberNamesTransform
  800. //{
  801. // typedef const char *result_type;
  802. // const char *operator()( const CZString &name ) const
  803. // {
  804. // return name.c_str();
  805. // }
  806. //};
  807. union ValueHolder {
  808. LargestInt int_;
  809. LargestUInt uint_;
  810. double real_;
  811. bool bool_;
  812. char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
  813. ObjectValues* map_;
  814. } value_;
  815. ValueType type_ : 8;
  816. unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
  817. // If not allocated_, string_ must be null-terminated.
  818. CommentInfo* comments_;
  819. // [start, limit) byte offsets in the source JSON text from which this Value
  820. // was extracted.
  821. size_t start_;
  822. size_t limit_;
  823. };
  824. /** \brief Experimental and untested: represents an element of the "path" to
  825. * access a node.
  826. */
  827. class JSON_API PathArgument {
  828. public:
  829. friend class Path;
  830. PathArgument();
  831. PathArgument(ArrayIndex index);
  832. PathArgument(const char* key);
  833. PathArgument(const std::string& key);
  834. private:
  835. enum Kind {
  836. kindNone = 0,
  837. kindIndex,
  838. kindKey
  839. };
  840. std::string key_;
  841. ArrayIndex index_;
  842. Kind kind_;
  843. };
  844. /** \brief Experimental and untested: represents a "path" to access a node.
  845. *
  846. * Syntax:
  847. * - "." => root node
  848. * - ".[n]" => elements at index 'n' of root node (an array value)
  849. * - ".name" => member named 'name' of root node (an object value)
  850. * - ".name1.name2.name3"
  851. * - ".[0][1][2].name1[3]"
  852. * - ".%" => member name is provided as parameter
  853. * - ".[%]" => index is provided as parameter
  854. */
  855. class JSON_API Path {
  856. public:
  857. Path(const std::string& path,
  858. const PathArgument& a1 = PathArgument(),
  859. const PathArgument& a2 = PathArgument(),
  860. const PathArgument& a3 = PathArgument(),
  861. const PathArgument& a4 = PathArgument(),
  862. const PathArgument& a5 = PathArgument());
  863. const Value& resolve(const Value& root) const;
  864. Value resolve(const Value& root, const Value& defaultValue) const;
  865. /// Creates the "path" to access the specified node and returns a reference on
  866. /// the node.
  867. Value& make(Value& root) const;
  868. private:
  869. typedef std::vector<const PathArgument*> InArgs;
  870. typedef std::vector<PathArgument> Args;
  871. void makePath(const std::string& path, const InArgs& in);
  872. void addPathInArg(const std::string& path,
  873. const InArgs& in,
  874. InArgs::const_iterator& itInArg,
  875. PathArgument::Kind kind);
  876. void invalidPath(const std::string& path, int location);
  877. Args args_;
  878. };
  879. /** \brief base class for Value iterators.
  880. *
  881. */
  882. class JSON_API ValueIteratorBase {
  883. public:
  884. typedef std::bidirectional_iterator_tag iterator_category;
  885. typedef unsigned int size_t;
  886. typedef int difference_type;
  887. typedef ValueIteratorBase SelfType;
  888. bool operator==(const SelfType& other) const { return isEqual(other); }
  889. bool operator!=(const SelfType& other) const { return !isEqual(other); }
  890. difference_type operator-(const SelfType& other) const {
  891. return other.computeDistance(*this);
  892. }
  893. /// Return either the index or the member name of the referenced value as a
  894. /// Value.
  895. Value key() const;
  896. /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
  897. UInt index() const;
  898. /// Return the member name of the referenced Value, or "" if it is not an
  899. /// objectValue.
  900. /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
  901. std::string name() const;
  902. /// Return the member name of the referenced Value. "" if it is not an
  903. /// objectValue.
  904. /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
  905. JSONCPP_DEPRECATED("Use `key = name();` instead.")
  906. char const* memberName() const;
  907. /// Return the member name of the referenced Value, or NULL if it is not an
  908. /// objectValue.
  909. /// \note Better version than memberName(). Allows embedded nulls.
  910. char const* memberName(char const** end) const;
  911. protected:
  912. Value& deref() const;
  913. void increment();
  914. void decrement();
  915. difference_type computeDistance(const SelfType& other) const;
  916. bool isEqual(const SelfType& other) const;
  917. void copy(const SelfType& other);
  918. private:
  919. Value::ObjectValues::iterator current_;
  920. // Indicates that iterator is for a null value.
  921. bool isNull_;
  922. public:
  923. // For some reason, BORLAND needs these at the end, rather
  924. // than earlier. No idea why.
  925. ValueIteratorBase();
  926. explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
  927. };
  928. /** \brief const iterator for object and array value.
  929. *
  930. */
  931. class JSON_API ValueConstIterator : public ValueIteratorBase {
  932. friend class Value;
  933. public:
  934. typedef const Value value_type;
  935. //typedef unsigned int size_t;
  936. //typedef int difference_type;
  937. typedef const Value& reference;
  938. typedef const Value* pointer;
  939. typedef ValueConstIterator SelfType;
  940. ValueConstIterator();
  941. ValueConstIterator(ValueIterator const& other);
  942. private:
  943. /*! \internal Use by Value to create an iterator.
  944. */
  945. explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
  946. public:
  947. SelfType& operator=(const ValueIteratorBase& other);
  948. SelfType operator++(int) {
  949. SelfType temp(*this);
  950. ++*this;
  951. return temp;
  952. }
  953. SelfType operator--(int) {
  954. SelfType temp(*this);
  955. --*this;
  956. return temp;
  957. }
  958. SelfType& operator--() {
  959. decrement();
  960. return *this;
  961. }
  962. SelfType& operator++() {
  963. increment();
  964. return *this;
  965. }
  966. reference operator*() const { return deref(); }
  967. pointer operator->() const { return &deref(); }
  968. };
  969. /** \brief Iterator for object and array value.
  970. */
  971. class JSON_API ValueIterator : public ValueIteratorBase {
  972. friend class Value;
  973. public:
  974. typedef Value value_type;
  975. typedef unsigned int size_t;
  976. typedef int difference_type;
  977. typedef Value& reference;
  978. typedef Value* pointer;
  979. typedef ValueIterator SelfType;
  980. ValueIterator();
  981. explicit ValueIterator(const ValueConstIterator& other);
  982. ValueIterator(const ValueIterator& other);
  983. private:
  984. /*! \internal Use by Value to create an iterator.
  985. */
  986. explicit ValueIterator(const Value::ObjectValues::iterator& current);
  987. public:
  988. SelfType& operator=(const SelfType& other);
  989. SelfType operator++(int) {
  990. SelfType temp(*this);
  991. ++*this;
  992. return temp;
  993. }
  994. SelfType operator--(int) {
  995. SelfType temp(*this);
  996. --*this;
  997. return temp;
  998. }
  999. SelfType& operator--() {
  1000. decrement();
  1001. return *this;
  1002. }
  1003. SelfType& operator++() {
  1004. increment();
  1005. return *this;
  1006. }
  1007. reference operator*() const { return deref(); }
  1008. pointer operator->() const { return &deref(); }
  1009. };
  1010. } // namespace Json
  1011. namespace std {
  1012. /// Specialize std::swap() for Json::Value.
  1013. template<>
  1014. inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
  1015. }
  1016. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1017. #pragma warning(pop)
  1018. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1019. #endif // CPPTL_JSON_H_INCLUDED
  1020. // //////////////////////////////////////////////////////////////////////
  1021. // End of content of file: include/json/value.h
  1022. // //////////////////////////////////////////////////////////////////////
  1023. // //////////////////////////////////////////////////////////////////////
  1024. // Beginning of content of file: include/json/reader.h
  1025. // //////////////////////////////////////////////////////////////////////
  1026. // Copyright 2007-2010 Baptiste Lepilleur
  1027. // Distributed under MIT license, or public domain if desired and
  1028. // recognized in your jurisdiction.
  1029. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  1030. #ifndef CPPTL_JSON_READER_H_INCLUDED
  1031. #define CPPTL_JSON_READER_H_INCLUDED
  1032. #if !defined(JSON_IS_AMALGAMATION)
  1033. #include "features.h"
  1034. #include "value.h"
  1035. #endif // if !defined(JSON_IS_AMALGAMATION)
  1036. #include <deque>
  1037. #include <iosfwd>
  1038. #include <stack>
  1039. #include <string>
  1040. #include <istream>
  1041. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  1042. // be used by...
  1043. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1044. #pragma warning(push)
  1045. #pragma warning(disable : 4251)
  1046. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1047. namespace Json {
  1048. /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
  1049. *Value.
  1050. *
  1051. * \deprecated Use CharReader and CharReaderBuilder.
  1052. */
  1053. class JSON_API Reader {
  1054. public:
  1055. typedef char Char;
  1056. typedef const Char* Location;
  1057. /** \brief An error tagged with where in the JSON text it was encountered.
  1058. *
  1059. * The offsets give the [start, limit) range of bytes within the text. Note
  1060. * that this is bytes, not codepoints.
  1061. *
  1062. */
  1063. struct StructuredError {
  1064. size_t offset_start;
  1065. size_t offset_limit;
  1066. std::string message;
  1067. };
  1068. /** \brief Constructs a Reader allowing all features
  1069. * for parsing.
  1070. */
  1071. Reader();
  1072. /** \brief Constructs a Reader allowing the specified feature set
  1073. * for parsing.
  1074. */
  1075. Reader(const Features& features);
  1076. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  1077. * document.
  1078. * \param document UTF-8 encoded string containing the document to read.
  1079. * \param root [out] Contains the root value of the document if it was
  1080. * successfully parsed.
  1081. * \param collectComments \c true to collect comment and allow writing them
  1082. * back during
  1083. * serialization, \c false to discard comments.
  1084. * This parameter is ignored if
  1085. * Features::allowComments_
  1086. * is \c false.
  1087. * \return \c true if the document was successfully parsed, \c false if an
  1088. * error occurred.
  1089. */
  1090. bool
  1091. parse(const std::string& document, Value& root, bool collectComments = true);
  1092. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  1093. document.
  1094. * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
  1095. document to read.
  1096. * \param endDoc Pointer on the end of the UTF-8 encoded string of the
  1097. document to read.
  1098. * Must be >= beginDoc.
  1099. * \param root [out] Contains the root value of the document if it was
  1100. * successfully parsed.
  1101. * \param collectComments \c true to collect comment and allow writing them
  1102. back during
  1103. * serialization, \c false to discard comments.
  1104. * This parameter is ignored if
  1105. Features::allowComments_
  1106. * is \c false.
  1107. * \return \c true if the document was successfully parsed, \c false if an
  1108. error occurred.
  1109. */
  1110. bool parse(const char* beginDoc,
  1111. const char* endDoc,
  1112. Value& root,
  1113. bool collectComments = true);
  1114. /// \brief Parse from input stream.
  1115. /// \see Json::operator>>(std::istream&, Json::Value&).
  1116. bool parse(std::istream& is, Value& root, bool collectComments = true);
  1117. /** \brief Returns a user friendly string that list errors in the parsed
  1118. * document.
  1119. * \return Formatted error message with the list of errors with their location
  1120. * in
  1121. * the parsed document. An empty string is returned if no error
  1122. * occurred
  1123. * during parsing.
  1124. * \deprecated Use getFormattedErrorMessages() instead (typo fix).
  1125. */
  1126. JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
  1127. std::string getFormatedErrorMessages() const;
  1128. /** \brief Returns a user friendly string that list errors in the parsed
  1129. * document.
  1130. * \return Formatted error message with the list of errors with their location
  1131. * in
  1132. * the parsed document. An empty string is returned if no error
  1133. * occurred
  1134. * during parsing.
  1135. */
  1136. std::string getFormattedErrorMessages() const;
  1137. /** \brief Returns a vector of structured errors encounted while parsing.
  1138. * \return A (possibly empty) vector of StructuredError objects. Currently
  1139. * only one error can be returned, but the caller should tolerate
  1140. * multiple
  1141. * errors. This can occur if the parser recovers from a non-fatal
  1142. * parse error and then encounters additional errors.
  1143. */
  1144. std::vector<StructuredError> getStructuredErrors() const;
  1145. /** \brief Add a semantic error message.
  1146. * \param value JSON Value location associated with the error
  1147. * \param message The error message.
  1148. * \return \c true if the error was successfully added, \c false if the
  1149. * Value offset exceeds the document size.
  1150. */
  1151. bool pushError(const Value& value, const std::string& message);
  1152. /** \brief Add a semantic error message with extra context.
  1153. * \param value JSON Value location associated with the error
  1154. * \param message The error message.
  1155. * \param extra Additional JSON Value location to contextualize the error
  1156. * \return \c true if the error was successfully added, \c false if either
  1157. * Value offset exceeds the document size.
  1158. */
  1159. bool pushError(const Value& value, const std::string& message, const Value& extra);
  1160. /** \brief Return whether there are any errors.
  1161. * \return \c true if there are no errors to report \c false if
  1162. * errors have occurred.
  1163. */
  1164. bool good() const;
  1165. private:
  1166. enum TokenType {
  1167. tokenEndOfStream = 0,
  1168. tokenObjectBegin,
  1169. tokenObjectEnd,
  1170. tokenArrayBegin,
  1171. tokenArrayEnd,
  1172. tokenString,
  1173. tokenNumber,
  1174. tokenTrue,
  1175. tokenFalse,
  1176. tokenNull,
  1177. tokenArraySeparator,
  1178. tokenMemberSeparator,
  1179. tokenComment,
  1180. tokenError
  1181. };
  1182. class Token {
  1183. public:
  1184. TokenType type_;
  1185. Location start_;
  1186. Location end_;
  1187. };
  1188. class ErrorInfo {
  1189. public:
  1190. Token token_;
  1191. std::string message_;
  1192. Location extra_;
  1193. };
  1194. typedef std::deque<ErrorInfo> Errors;
  1195. bool readToken(Token& token);
  1196. void skipSpaces();
  1197. bool match(Location pattern, int patternLength);
  1198. bool readComment();
  1199. bool readCStyleComment();
  1200. bool readCppStyleComment();
  1201. bool readString();
  1202. void readNumber();
  1203. bool readValue();
  1204. bool readObject(Token& token);
  1205. bool readArray(Token& token);
  1206. bool decodeNumber(Token& token);
  1207. bool decodeNumber(Token& token, Value& decoded);
  1208. bool decodeString(Token& token);
  1209. bool decodeString(Token& token, std::string& decoded);
  1210. bool decodeDouble(Token& token);
  1211. bool decodeDouble(Token& token, Value& decoded);
  1212. bool decodeUnicodeCodePoint(Token& token,
  1213. Location& current,
  1214. Location end,
  1215. unsigned int& unicode);
  1216. bool decodeUnicodeEscapeSequence(Token& token,
  1217. Location& current,
  1218. Location end,
  1219. unsigned int& unicode);
  1220. bool addError(const std::string& message, Token& token, Location extra = 0);
  1221. bool recoverFromError(TokenType skipUntilToken);
  1222. bool addErrorAndRecover(const std::string& message,
  1223. Token& token,
  1224. TokenType skipUntilToken);
  1225. void skipUntilSpace();
  1226. Value& currentValue();
  1227. Char getNextChar();
  1228. void
  1229. getLocationLineAndColumn(Location location, int& line, int& column) const;
  1230. std::string getLocationLineAndColumn(Location location) const;
  1231. void addComment(Location begin, Location end, CommentPlacement placement);
  1232. void skipCommentTokens(Token& token);
  1233. typedef std::stack<Value*> Nodes;
  1234. Nodes nodes_;
  1235. Errors errors_;
  1236. std::string document_;
  1237. Location begin_;
  1238. Location end_;
  1239. Location current_;
  1240. Location lastValueEnd_;
  1241. Value* lastValue_;
  1242. std::string commentsBefore_;
  1243. Features features_;
  1244. bool collectComments_;
  1245. }; // Reader
  1246. /** Interface for reading JSON from a char array.
  1247. */
  1248. class JSON_API CharReader {
  1249. public:
  1250. virtual ~CharReader() {}
  1251. /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
  1252. document.
  1253. * The document must be a UTF-8 encoded string containing the document to read.
  1254. *
  1255. * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
  1256. document to read.
  1257. * \param endDoc Pointer on the end of the UTF-8 encoded string of the
  1258. document to read.
  1259. * Must be >= beginDoc.
  1260. * \param root [out] Contains the root value of the document if it was
  1261. * successfully parsed.
  1262. * \param errs [out] Formatted error messages (if not NULL)
  1263. * a user friendly string that lists errors in the parsed
  1264. * document.
  1265. * \return \c true if the document was successfully parsed, \c false if an
  1266. error occurred.
  1267. */
  1268. virtual bool parse(
  1269. char const* beginDoc, char const* endDoc,
  1270. Value* root, std::string* errs) = 0;
  1271. class JSON_API Factory {
  1272. public:
  1273. virtual ~Factory() {}
  1274. /** \brief Allocate a CharReader via operator new().
  1275. * \throw std::exception if something goes wrong (e.g. invalid settings)
  1276. */
  1277. virtual CharReader* newCharReader() const = 0;
  1278. }; // Factory
  1279. }; // CharReader
  1280. /** \brief Build a CharReader implementation.
  1281. Usage:
  1282. \code
  1283. using namespace Json;
  1284. CharReaderBuilder builder;
  1285. builder["collectComments"] = false;
  1286. Value value;
  1287. std::string errs;
  1288. bool ok = parseFromStream(builder, std::cin, &value, &errs);
  1289. \endcode
  1290. */
  1291. class JSON_API CharReaderBuilder : public CharReader::Factory {
  1292. public:
  1293. // Note: We use a Json::Value so that we can add data-members to this class
  1294. // without a major version bump.
  1295. /** Configuration of this builder.
  1296. These are case-sensitive.
  1297. Available settings (case-sensitive):
  1298. - `"collectComments": false or true`
  1299. - true to collect comment and allow writing them
  1300. back during serialization, false to discard comments.
  1301. This parameter is ignored if allowComments is false.
  1302. - `"allowComments": false or true`
  1303. - true if comments are allowed.
  1304. - `"strictRoot": false or true`
  1305. - true if root must be either an array or an object value
  1306. - `"allowDroppedNullPlaceholders": false or true`
  1307. - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
  1308. - `"allowNumericKeys": false or true`
  1309. - true if numeric object keys are allowed.
  1310. - `"allowSingleQuotes": false or true`
  1311. - true if '' are allowed for strings (both keys and values)
  1312. - `"stackLimit": integer`
  1313. - Exceeding stackLimit (recursive depth of `readValue()`) will
  1314. cause an exception.
  1315. - This is a security issue (seg-faults caused by deeply nested JSON),
  1316. so the default is low.
  1317. - `"failIfExtra": false or true`
  1318. - If true, `parse()` returns false when extra non-whitespace trails
  1319. the JSON value in the input string.
  1320. - `"rejectDupKeys": false or true`
  1321. - If true, `parse()` returns false when a key is duplicated within an object.
  1322. - `"allowSpecialFloats": false or true`
  1323. - If true, special float values (NaNs and infinities) are allowed
  1324. and their values are lossfree restorable.
  1325. You can examine 'settings_` yourself
  1326. to see the defaults. You can also write and read them just like any
  1327. JSON Value.
  1328. \sa setDefaults()
  1329. */
  1330. Json::Value settings_;
  1331. CharReaderBuilder();
  1332. ~CharReaderBuilder() override;
  1333. CharReader* newCharReader() const override;
  1334. /** \return true if 'settings' are legal and consistent;
  1335. * otherwise, indicate bad settings via 'invalid'.
  1336. */
  1337. bool validate(Json::Value* invalid) const;
  1338. /** A simple way to update a specific setting.
  1339. */
  1340. Value& operator[](std::string key);
  1341. /** Called by ctor, but you can use this to reset settings_.
  1342. * \pre 'settings' != NULL (but Json::null is fine)
  1343. * \remark Defaults:
  1344. * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
  1345. */
  1346. static void setDefaults(Json::Value* settings);
  1347. /** Same as old Features::strictMode().
  1348. * \pre 'settings' != NULL (but Json::null is fine)
  1349. * \remark Defaults:
  1350. * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
  1351. */
  1352. static void strictMode(Json::Value* settings);
  1353. };
  1354. /** Consume entire stream and use its begin/end.
  1355. * Someday we might have a real StreamReader, but for now this
  1356. * is convenient.
  1357. */
  1358. bool JSON_API parseFromStream(
  1359. CharReader::Factory const&,
  1360. std::istream&,
  1361. Value* root, std::string* errs);
  1362. /** \brief Read from 'sin' into 'root'.
  1363. Always keep comments from the input JSON.
  1364. This can be used to read a file into a particular sub-object.
  1365. For example:
  1366. \code
  1367. Json::Value root;
  1368. cin >> root["dir"]["file"];
  1369. cout << root;
  1370. \endcode
  1371. Result:
  1372. \verbatim
  1373. {
  1374. "dir": {
  1375. "file": {
  1376. // The input stream JSON would be nested here.
  1377. }
  1378. }
  1379. }
  1380. \endverbatim
  1381. \throw std::exception on parse error.
  1382. \see Json::operator<<()
  1383. */
  1384. JSON_API std::istream& operator>>(std::istream&, Value&);
  1385. } // namespace Json
  1386. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1387. #pragma warning(pop)
  1388. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1389. #endif // CPPTL_JSON_READER_H_INCLUDED
  1390. // //////////////////////////////////////////////////////////////////////
  1391. // End of content of file: include/json/reader.h
  1392. // //////////////////////////////////////////////////////////////////////
  1393. // //////////////////////////////////////////////////////////////////////
  1394. // Beginning of content of file: include/json/writer.h
  1395. // //////////////////////////////////////////////////////////////////////
  1396. // Copyright 2007-2010 Baptiste Lepilleur
  1397. // Distributed under MIT license, or public domain if desired and
  1398. // recognized in your jurisdiction.
  1399. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  1400. #ifndef JSON_WRITER_H_INCLUDED
  1401. #define JSON_WRITER_H_INCLUDED
  1402. #if !defined(JSON_IS_AMALGAMATION)
  1403. #include "value.h"
  1404. #endif // if !defined(JSON_IS_AMALGAMATION)
  1405. #include <vector>
  1406. #include <string>
  1407. #include <ostream>
  1408. // Disable warning C4251: <data member>: <type> needs to have dll-interface to
  1409. // be used by...
  1410. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1411. #pragma warning(push)
  1412. #pragma warning(disable : 4251)
  1413. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1414. namespace Json {
  1415. class Value;
  1416. /**
  1417. Usage:
  1418. \code
  1419. using namespace Json;
  1420. void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
  1421. std::unique_ptr<StreamWriter> const writer(
  1422. factory.newStreamWriter());
  1423. writer->write(value, &std::cout);
  1424. std::cout << std::endl; // add lf and flush
  1425. }
  1426. \endcode
  1427. */
  1428. class JSON_API StreamWriter {
  1429. protected:
  1430. std::ostream* sout_; // not owned; will not delete
  1431. public:
  1432. StreamWriter();
  1433. virtual ~StreamWriter();
  1434. /** Write Value into document as configured in sub-class.
  1435. Do not take ownership of sout, but maintain a reference during function.
  1436. \pre sout != NULL
  1437. \return zero on success (For now, we always return zero, so check the stream instead.)
  1438. \throw std::exception possibly, depending on configuration
  1439. */
  1440. virtual int write(Value const& root, std::ostream* sout) = 0;
  1441. /** \brief A simple abstract factory.
  1442. */
  1443. class JSON_API Factory {
  1444. public:
  1445. virtual ~Factory();
  1446. /** \brief Allocate a CharReader via operator new().
  1447. * \throw std::exception if something goes wrong (e.g. invalid settings)
  1448. */
  1449. virtual StreamWriter* newStreamWriter() const = 0;
  1450. }; // Factory
  1451. }; // StreamWriter
  1452. /** \brief Write into stringstream, then return string, for convenience.
  1453. * A StreamWriter will be created from the factory, used, and then deleted.
  1454. */
  1455. std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
  1456. /** \brief Build a StreamWriter implementation.
  1457. Usage:
  1458. \code
  1459. using namespace Json;
  1460. Value value = ...;
  1461. StreamWriterBuilder builder;
  1462. builder["commentStyle"] = "None";
  1463. builder["indentation"] = " "; // or whatever you like
  1464. std::unique_ptr<Json::StreamWriter> writer(
  1465. builder.newStreamWriter());
  1466. writer->write(value, &std::cout);
  1467. std::cout << std::endl; // add lf and flush
  1468. \endcode
  1469. */
  1470. class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
  1471. public:
  1472. // Note: We use a Json::Value so that we can add data-members to this class
  1473. // without a major version bump.
  1474. /** Configuration of this builder.
  1475. Available settings (case-sensitive):
  1476. - "commentStyle": "None" or "All"
  1477. - "indentation": "<anything>"
  1478. - "enableYAMLCompatibility": false or true
  1479. - slightly change the whitespace around colons
  1480. - "dropNullPlaceholders": false or true
  1481. - Drop the "null" string from the writer's output for nullValues.
  1482. Strictly speaking, this is not valid JSON. But when the output is being
  1483. fed to a browser's Javascript, it makes for smaller output and the
  1484. browser can handle the output just fine.
  1485. - "useSpecialFloats": false or true
  1486. - If true, outputs non-finite floating point values in the following way:
  1487. NaN values as "NaN", positive infinity as "Infinity", and negative infinity
  1488. as "-Infinity".
  1489. You can examine 'settings_` yourself
  1490. to see the defaults. You can also write and read them just like any
  1491. JSON Value.
  1492. \sa setDefaults()
  1493. */
  1494. Json::Value settings_;
  1495. StreamWriterBuilder();
  1496. ~StreamWriterBuilder() override;
  1497. /**
  1498. * \throw std::exception if something goes wrong (e.g. invalid settings)
  1499. */
  1500. StreamWriter* newStreamWriter() const override;
  1501. /** \return true if 'settings' are legal and consistent;
  1502. * otherwise, indicate bad settings via 'invalid'.
  1503. */
  1504. bool validate(Json::Value* invalid) const;
  1505. /** A simple way to update a specific setting.
  1506. */
  1507. Value& operator[](std::string key);
  1508. /** Called by ctor, but you can use this to reset settings_.
  1509. * \pre 'settings' != NULL (but Json::null is fine)
  1510. * \remark Defaults:
  1511. * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
  1512. */
  1513. static void setDefaults(Json::Value* settings);
  1514. };
  1515. /** \brief Abstract class for writers.
  1516. * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
  1517. */
  1518. class JSON_API Writer {
  1519. public:
  1520. virtual ~Writer();
  1521. virtual std::string write(const Value& root) = 0;
  1522. };
  1523. /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
  1524. *without formatting (not human friendly).
  1525. *
  1526. * The JSON document is written in a single line. It is not intended for 'human'
  1527. *consumption,
  1528. * but may be useful to support feature such as RPC where bandwidth is limited.
  1529. * \sa Reader, Value
  1530. * \deprecated Use StreamWriterBuilder.
  1531. */
  1532. class JSON_API FastWriter : public Writer {
  1533. public:
  1534. FastWriter();
  1535. ~FastWriter() override {}
  1536. void enableYAMLCompatibility();
  1537. /** \brief Drop the "null" string from the writer's output for nullValues.
  1538. * Strictly speaking, this is not valid JSON. But when the output is being
  1539. * fed to a browser's Javascript, it makes for smaller output and the
  1540. * browser can handle the output just fine.
  1541. */
  1542. void dropNullPlaceholders();
  1543. void omitEndingLineFeed();
  1544. public: // overridden from Writer
  1545. std::string write(const Value& root) override;
  1546. private:
  1547. void writeValue(const Value& value);
  1548. std::string document_;
  1549. bool yamlCompatiblityEnabled_;
  1550. bool dropNullPlaceholders_;
  1551. bool omitEndingLineFeed_;
  1552. };
  1553. /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
  1554. *human friendly way.
  1555. *
  1556. * The rules for line break and indent are as follow:
  1557. * - Object value:
  1558. * - if empty then print {} without indent and line break
  1559. * - if not empty the print '{', line break & indent, print one value per
  1560. *line
  1561. * and then unindent and line break and print '}'.
  1562. * - Array value:
  1563. * - if empty then print [] without indent and line break
  1564. * - if the array contains no object value, empty array or some other value
  1565. *types,
  1566. * and all the values fit on one lines, then print the array on a single
  1567. *line.
  1568. * - otherwise, it the values do not fit on one line, or the array contains
  1569. * object or non empty array, then print one value per line.
  1570. *
  1571. * If the Value have comments then they are outputed according to their
  1572. *#CommentPlacement.
  1573. *
  1574. * \sa Reader, Value, Value::setComment()
  1575. * \deprecated Use StreamWriterBuilder.
  1576. */
  1577. class JSON_API StyledWriter : public Writer {
  1578. public:
  1579. StyledWriter();
  1580. ~StyledWriter() override {}
  1581. public: // overridden from Writer
  1582. /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
  1583. * \param root Value to serialize.
  1584. * \return String containing the JSON document that represents the root value.
  1585. */
  1586. std::string write(const Value& root) override;
  1587. private:
  1588. void writeValue(const Value& value);
  1589. void writeArrayValue(const Value& value);
  1590. bool isMultineArray(const Value& value);
  1591. void pushValue(const std::string& value);
  1592. void writeIndent();
  1593. void writeWithIndent(const std::string& value);
  1594. void indent();
  1595. void unindent();
  1596. void writeCommentBeforeValue(const Value& root);
  1597. void writeCommentAfterValueOnSameLine(const Value& root);
  1598. bool hasCommentForValue(const Value& value);
  1599. static std::string normalizeEOL(const std::string& text);
  1600. typedef std::vector<std::string> ChildValues;
  1601. ChildValues childValues_;
  1602. std::string document_;
  1603. std::string indentString_;
  1604. int rightMargin_;
  1605. int indentSize_;
  1606. bool addChildValues_;
  1607. };
  1608. /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
  1609. human friendly way,
  1610. to a stream rather than to a string.
  1611. *
  1612. * The rules for line break and indent are as follow:
  1613. * - Object value:
  1614. * - if empty then print {} without indent and line break
  1615. * - if not empty the print '{', line break & indent, print one value per
  1616. line
  1617. * and then unindent and line break and print '}'.
  1618. * - Array value:
  1619. * - if empty then print [] without indent and line break
  1620. * - if the array contains no object value, empty array or some other value
  1621. types,
  1622. * and all the values fit on one lines, then print the array on a single
  1623. line.
  1624. * - otherwise, it the values do not fit on one line, or the array contains
  1625. * object or non empty array, then print one value per line.
  1626. *
  1627. * If the Value have comments then they are outputed according to their
  1628. #CommentPlacement.
  1629. *
  1630. * \param indentation Each level will be indented by this amount extra.
  1631. * \sa Reader, Value, Value::setComment()
  1632. * \deprecated Use StreamWriterBuilder.
  1633. */
  1634. class JSON_API StyledStreamWriter {
  1635. public:
  1636. StyledStreamWriter(std::string indentation = "\t");
  1637. ~StyledStreamWriter() {}
  1638. public:
  1639. /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
  1640. * \param out Stream to write to. (Can be ostringstream, e.g.)
  1641. * \param root Value to serialize.
  1642. * \note There is no point in deriving from Writer, since write() should not
  1643. * return a value.
  1644. */
  1645. void write(std::ostream& out, const Value& root);
  1646. private:
  1647. void writeValue(const Value& value);
  1648. void writeArrayValue(const Value& value);
  1649. bool isMultineArray(const Value& value);
  1650. void pushValue(const std::string& value);
  1651. void writeIndent();
  1652. void writeWithIndent(const std::string& value);
  1653. void indent();
  1654. void unindent();
  1655. void writeCommentBeforeValue(const Value& root);
  1656. void writeCommentAfterValueOnSameLine(const Value& root);
  1657. bool hasCommentForValue(const Value& value);
  1658. static std::string normalizeEOL(const std::string& text);
  1659. typedef std::vector<std::string> ChildValues;
  1660. ChildValues childValues_;
  1661. std::ostream* document_;
  1662. std::string indentString_;
  1663. int rightMargin_;
  1664. std::string indentation_;
  1665. bool addChildValues_ : 1;
  1666. bool indented_ : 1;
  1667. };
  1668. #if defined(JSON_HAS_INT64)
  1669. std::string JSON_API valueToString(Int value);
  1670. std::string JSON_API valueToString(UInt value);
  1671. #endif // if defined(JSON_HAS_INT64)
  1672. std::string JSON_API valueToString(LargestInt value);
  1673. std::string JSON_API valueToString(LargestUInt value);
  1674. std::string JSON_API valueToString(double value);
  1675. std::string JSON_API valueToString(bool value);
  1676. std::string JSON_API valueToQuotedString(const char* value);
  1677. /// \brief Output using the StyledStreamWriter.
  1678. /// \see Json::operator>>()
  1679. JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
  1680. } // namespace Json
  1681. #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1682. #pragma warning(pop)
  1683. #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
  1684. #endif // JSON_WRITER_H_INCLUDED
  1685. // //////////////////////////////////////////////////////////////////////
  1686. // End of content of file: include/json/writer.h
  1687. // //////////////////////////////////////////////////////////////////////
  1688. // //////////////////////////////////////////////////////////////////////
  1689. // Beginning of content of file: include/json/assertions.h
  1690. // //////////////////////////////////////////////////////////////////////
  1691. // Copyright 2007-2010 Baptiste Lepilleur
  1692. // Distributed under MIT license, or public domain if desired and
  1693. // recognized in your jurisdiction.
  1694. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  1695. #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
  1696. #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
  1697. #include <stdlib.h>
  1698. #include <sstream>
  1699. #if !defined(JSON_IS_AMALGAMATION)
  1700. #include "config.h"
  1701. #endif // if !defined(JSON_IS_AMALGAMATION)
  1702. /** It should not be possible for a maliciously designed file to
  1703. * cause an abort() or seg-fault, so these macros are used only
  1704. * for pre-condition violations and internal logic errors.
  1705. */
  1706. #if JSON_USE_EXCEPTION
  1707. // @todo <= add detail about condition in exception
  1708. # define JSON_ASSERT(condition) \
  1709. {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
  1710. # define JSON_FAIL_MESSAGE(message) \
  1711. { \
  1712. std::ostringstream oss; oss << message; \
  1713. Json::throwLogicError(oss.str()); \
  1714. abort(); \
  1715. }
  1716. #else // JSON_USE_EXCEPTION
  1717. # define JSON_ASSERT(condition) assert(condition)
  1718. // The call to assert() will show the failure message in debug builds. In
  1719. // release builds we abort, for a core-dump or debugger.
  1720. # define JSON_FAIL_MESSAGE(message) \
  1721. { \
  1722. std::ostringstream oss; oss << message; \
  1723. assert(false && oss.str().c_str()); \
  1724. abort(); \
  1725. }
  1726. #endif
  1727. #define JSON_ASSERT_MESSAGE(condition, message) \
  1728. if (!(condition)) { \
  1729. JSON_FAIL_MESSAGE(message); \
  1730. }
  1731. #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
  1732. // //////////////////////////////////////////////////////////////////////
  1733. // End of content of file: include/json/assertions.h
  1734. // //////////////////////////////////////////////////////////////////////
  1735. #endif //ifndef JSON_AMALGATED_H_INCLUDED