1 /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
2 /// It is intended to be used with #include "json/json.h"
4 // //////////////////////////////////////////////////////////////////////
5 // Beginning of content of file: LICENSE
6 // //////////////////////////////////////////////////////////////////////
9 The JsonCpp library's source code, including accompanying documentation,
10 tests and demonstration applications, are licensed under the following
13 Baptiste Lepilleur and The JsonCpp Authors explicitly disclaim copyright in all
14 jurisdictions which recognize such a disclaimer. In such jurisdictions,
15 this software is released into the Public Domain.
17 In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
18 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur and
19 The JsonCpp Authors, and is released under the terms of the MIT License (see below).
21 In jurisdictions which recognize Public Domain property, the user of this
22 software may choose to accept it either as 1) Public Domain, 2) under the
23 conditions of the MIT License (see below), or 3) under the terms of dual
24 Public Domain/MIT License conditions described here, as they choose.
26 The MIT License is about as close to Public Domain as a license can get, and is
27 described in clear, concise terms at:
29 http://en.wikipedia.org/wiki/MIT_License
31 The full text of the MIT License follows:
33 ========================================================================
34 Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
36 Permission is hereby granted, free of charge, to any person
37 obtaining a copy of this software and associated documentation
38 files (the "Software"), to deal in the Software without
39 restriction, including without limitation the rights to use, copy,
40 modify, merge, publish, distribute, sublicense, and/or sell copies
41 of the Software, and to permit persons to whom the Software is
42 furnished to do so, subject to the following conditions:
44 The above copyright notice and this permission notice shall be
45 included in all copies or substantial portions of the Software.
47 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
48 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
49 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
50 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
51 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
52 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
53 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
55 ========================================================================
58 The MIT license is compatible with both the GPL and commercial
59 software, affording one all of the rights of Public Domain with the
60 minor nuisance of being required to keep the above copyright notice
61 and license text in the source code. Note also that by accepting the
62 Public Domain "license" you can re-license your copy using whatever
67 // //////////////////////////////////////////////////////////////////////
68 // End of content of file: LICENSE
69 // //////////////////////////////////////////////////////////////////////
75 #ifndef JSON_AMALGATED_H_INCLUDED
76 # define JSON_AMALGATED_H_INCLUDED
77 /// If defined, indicates that the source file is amalgated
78 /// to prevent private header inclusion.
79 #define JSON_IS_AMALGAMATION
81 // //////////////////////////////////////////////////////////////////////
82 // Beginning of content of file: include/json/version.h
83 // //////////////////////////////////////////////////////////////////////
85 // DO NOT EDIT. This file (and "version") is generated by CMake.
86 // Run CMake configure step to update it.
87 #ifndef JSON_VERSION_H_INCLUDED
88 # define JSON_VERSION_H_INCLUDED
90 # define JSONCPP_VERSION_STRING "1.8.3"
91 # define JSONCPP_VERSION_MAJOR 1
92 # define JSONCPP_VERSION_MINOR 8
93 # define JSONCPP_VERSION_PATCH 3
94 # define JSONCPP_VERSION_QUALIFIER
95 # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
97 #ifdef JSONCPP_USING_SECURE_MEMORY
98 #undef JSONCPP_USING_SECURE_MEMORY
100 #define JSONCPP_USING_SECURE_MEMORY 0
101 // If non-zero, the library zeroes any memory that it has allocated before
102 // it frees its memory.
104 #endif // JSON_VERSION_H_INCLUDED
106 // //////////////////////////////////////////////////////////////////////
107 // End of content of file: include/json/version.h
108 // //////////////////////////////////////////////////////////////////////
115 // //////////////////////////////////////////////////////////////////////
116 // Beginning of content of file: include/json/config.h
117 // //////////////////////////////////////////////////////////////////////
119 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
120 // Distributed under MIT license, or public domain if desired and
121 // recognized in your jurisdiction.
122 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
124 #ifndef JSON_CONFIG_H_INCLUDED
125 #define JSON_CONFIG_H_INCLUDED
127 #include <string> //typedef String
128 #include <stdint.h> //typedef int64_t, uint64_t
130 /// If defined, indicates that json library is embedded in CppTL library.
131 //# define JSON_IN_CPPTL 1
133 /// If defined, indicates that json may leverage CppTL library
134 //# define JSON_USE_CPPTL 1
135 /// If defined, indicates that cpptl vector based map should be used instead of
137 /// as Value container.
138 //# define JSON_USE_CPPTL_SMALLMAP 1
140 // If non-zero, the library uses exceptions to report bad input instead of C
141 // assertion macros. The default is to use exceptions.
142 #ifndef JSON_USE_EXCEPTION
143 #define JSON_USE_EXCEPTION 1
146 /// If defined, indicates that the source file is amalgated
147 /// to prevent private header inclusion.
148 /// Remarks: it is automatically defined in the generated amalgated header.
149 // #define JSON_IS_AMALGAMATION
152 #include <cpptl/config.h>
153 #ifndef JSON_USE_CPPTL
154 #define JSON_USE_CPPTL 1
159 #define JSON_API CPPTL_API
160 #elif defined(JSON_DLL_BUILD)
161 #if defined(_MSC_VER) || defined(__MINGW32__)
162 #define JSON_API __declspec(dllexport)
163 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
164 #endif // if defined(_MSC_VER)
165 #elif defined(JSON_DLL)
166 #if defined(_MSC_VER) || defined(__MINGW32__)
167 #define JSON_API __declspec(dllimport)
168 #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
169 #endif // if defined(_MSC_VER)
170 #endif // ifdef JSON_IN_CPPTL
171 #if !defined(JSON_API)
175 // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
177 // Storages, and 64 bits integer support is disabled.
178 // #define JSON_NO_INT64 1
180 #if defined(_MSC_VER) // MSVC
181 # if _MSC_VER <= 1200 // MSVC 6
182 // Microsoft Visual Studio 6 only support conversion from __int64 to double
183 // (no conversion from unsigned __int64).
184 # define JSON_USE_INT64_DOUBLE_CONVERSION 1
185 // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
186 // characters in the debug information)
187 // All projects I've ever seen with VS6 were using this globally (not bothering
188 // with pragma push/pop).
189 # pragma warning(disable : 4786)
192 # if _MSC_VER >= 1500 // MSVC 2008
193 /// Indicates that the following function is deprecated.
194 # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
197 #endif // defined(_MSC_VER)
199 // In c++11 the override keyword allows you to explicity define that a function
200 // is intended to override the base-class version. This makes the code more
201 // managable and fixes a set of common hard-to-find bugs.
202 #if __cplusplus >= 201103L
203 # define JSONCPP_OVERRIDE override
204 # define JSONCPP_NOEXCEPT noexcept
205 #elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900
206 # define JSONCPP_OVERRIDE override
207 # define JSONCPP_NOEXCEPT throw()
208 #elif defined(_MSC_VER) && _MSC_VER >= 1900
209 # define JSONCPP_OVERRIDE override
210 # define JSONCPP_NOEXCEPT noexcept
212 # define JSONCPP_OVERRIDE
213 # define JSONCPP_NOEXCEPT throw()
216 #ifndef JSON_HAS_RVALUE_REFERENCES
218 #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
219 #define JSON_HAS_RVALUE_REFERENCES 1
220 #endif // MSVC >= 2010
223 #if __has_feature(cxx_rvalue_references)
224 #define JSON_HAS_RVALUE_REFERENCES 1
225 #endif // has_feature
227 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
228 #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
229 #define JSON_HAS_RVALUE_REFERENCES 1
230 #endif // GXX_EXPERIMENTAL
232 #endif // __clang__ || __GNUC__
234 #endif // not defined JSON_HAS_RVALUE_REFERENCES
236 #ifndef JSON_HAS_RVALUE_REFERENCES
237 #define JSON_HAS_RVALUE_REFERENCES 0
241 # if __has_extension(attribute_deprecated_with_message)
242 # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
244 #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
245 # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
246 # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
247 # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
248 # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
249 # endif // GNUC version
250 #endif // __clang__ || __GNUC__
252 #if !defined(JSONCPP_DEPRECATED)
253 #define JSONCPP_DEPRECATED(message)
254 #endif // if !defined(JSONCPP_DEPRECATED)
257 # define JSON_USE_INT64_DOUBLE_CONVERSION 1
260 #if !defined(JSON_IS_AMALGAMATION)
262 # include "version.h"
264 # if JSONCPP_USING_SECURE_MEMORY
265 # include "allocator.h" //typedef Allocator
268 #endif // if !defined(JSON_IS_AMALGAMATION)
272 typedef unsigned int UInt;
273 #if defined(JSON_NO_INT64)
274 typedef int LargestInt;
275 typedef unsigned int LargestUInt;
276 #undef JSON_HAS_INT64
277 #else // if defined(JSON_NO_INT64)
278 // For Microsoft Visual use specific types as long long is not supported
279 #if defined(_MSC_VER) // Microsoft Visual Studio
280 typedef __int64 Int64;
281 typedef unsigned __int64 UInt64;
282 #else // if defined(_MSC_VER) // Other platforms, use long long
283 typedef int64_t Int64;
284 typedef uint64_t UInt64;
285 #endif // if defined(_MSC_VER)
286 typedef Int64 LargestInt;
287 typedef UInt64 LargestUInt;
288 #define JSON_HAS_INT64
289 #endif // if defined(JSON_NO_INT64)
290 #if JSONCPP_USING_SECURE_MEMORY
291 #define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
292 #define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
293 #define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
294 #define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
295 #define JSONCPP_ISTREAM std::istream
297 #define JSONCPP_STRING std::string
298 #define JSONCPP_OSTRINGSTREAM std::ostringstream
299 #define JSONCPP_OSTREAM std::ostream
300 #define JSONCPP_ISTRINGSTREAM std::istringstream
301 #define JSONCPP_ISTREAM std::istream
302 #endif // if JSONCPP_USING_SECURE_MEMORY
303 } // end namespace Json
305 #endif // JSON_CONFIG_H_INCLUDED
307 // //////////////////////////////////////////////////////////////////////
308 // End of content of file: include/json/config.h
309 // //////////////////////////////////////////////////////////////////////
316 // //////////////////////////////////////////////////////////////////////
317 // Beginning of content of file: include/json/forwards.h
318 // //////////////////////////////////////////////////////////////////////
320 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
321 // Distributed under MIT license, or public domain if desired and
322 // recognized in your jurisdiction.
323 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
325 #ifndef JSON_FORWARDS_H_INCLUDED
326 #define JSON_FORWARDS_H_INCLUDED
328 #if !defined(JSON_IS_AMALGAMATION)
330 #endif // if !defined(JSON_IS_AMALGAMATION)
345 typedef unsigned int ArrayIndex;
350 class ValueIteratorBase;
352 class ValueConstIterator;
356 #endif // JSON_FORWARDS_H_INCLUDED
358 // //////////////////////////////////////////////////////////////////////
359 // End of content of file: include/json/forwards.h
360 // //////////////////////////////////////////////////////////////////////
367 // //////////////////////////////////////////////////////////////////////
368 // Beginning of content of file: include/json/features.h
369 // //////////////////////////////////////////////////////////////////////
371 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
372 // Distributed under MIT license, or public domain if desired and
373 // recognized in your jurisdiction.
374 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
376 #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
377 #define CPPTL_JSON_FEATURES_H_INCLUDED
379 #if !defined(JSON_IS_AMALGAMATION)
380 #include "forwards.h"
381 #endif // if !defined(JSON_IS_AMALGAMATION)
383 #pragma pack(push, 8)
387 /** \brief Configuration passed to reader and writer.
388 * This configuration object can be used to force the Reader or Writer
389 * to behave in a standard conforming way.
391 class JSON_API Features {
393 /** \brief A configuration that allows all features and assumes all strings
395 * - C & C++ comments are allowed
396 * - Root object can be any JSON value
397 * - Assumes Value strings are encoded in UTF-8
399 static Features all();
401 /** \brief A configuration that is strictly compatible with the JSON
403 * - Comments are forbidden.
404 * - Root object must be either an array or an object value.
405 * - Assumes Value strings are encoded in UTF-8
407 static Features strictMode();
409 /** \brief Initialize the configuration like JsonConfig::allFeatures;
413 /// \c true if comments are allowed. Default: \c true.
416 /// \c true if root must be either an array or an object value. Default: \c
420 /// \c true if dropped null placeholders are allowed. Default: \c false.
421 bool allowDroppedNullPlaceholders_;
423 /// \c true if numeric object key are allowed. Default: \c false.
424 bool allowNumericKeys_;
431 #endif // CPPTL_JSON_FEATURES_H_INCLUDED
433 // //////////////////////////////////////////////////////////////////////
434 // End of content of file: include/json/features.h
435 // //////////////////////////////////////////////////////////////////////
442 // //////////////////////////////////////////////////////////////////////
443 // Beginning of content of file: include/json/value.h
444 // //////////////////////////////////////////////////////////////////////
446 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
447 // Distributed under MIT license, or public domain if desired and
448 // recognized in your jurisdiction.
449 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
451 #ifndef CPPTL_JSON_H_INCLUDED
452 #define CPPTL_JSON_H_INCLUDED
454 #if !defined(JSON_IS_AMALGAMATION)
455 #include "forwards.h"
456 #endif // if !defined(JSON_IS_AMALGAMATION)
461 #ifndef JSON_USE_CPPTL_SMALLMAP
464 #include <cpptl/smallmap.h>
466 #ifdef JSON_USE_CPPTL
467 #include <cpptl/forwards.h>
470 //Conditional NORETURN attribute on the throw functions would:
471 // a) suppress false positives from static code analysis
472 // b) possibly improve optimization opportunities.
473 #if !defined(JSONCPP_NORETURN)
474 # if defined(_MSC_VER)
475 # define JSONCPP_NORETURN __declspec(noreturn)
476 # elif defined(__GNUC__)
477 # define JSONCPP_NORETURN __attribute__ ((__noreturn__))
479 # define JSONCPP_NORETURN
483 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
485 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
486 #pragma warning(push)
487 #pragma warning(disable : 4251)
488 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
490 #pragma pack(push, 8)
492 /** \brief JSON (JavaScript Object Notation).
496 /** Base class for all exceptions we throw.
498 * We use nothing but these internally. Of course, STL can throw others.
500 class JSON_API Exception : public std::exception {
502 Exception(JSONCPP_STRING const& msg);
503 ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
504 char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
509 /** Exceptions which the user cannot easily avoid.
511 * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
513 * \remark derived from Json::Exception
515 class JSON_API RuntimeError : public Exception {
517 RuntimeError(JSONCPP_STRING const& msg);
520 /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
522 * These are precondition-violations (user bugs) and internal errors (our bugs).
524 * \remark derived from Json::Exception
526 class JSON_API LogicError : public Exception {
528 LogicError(JSONCPP_STRING const& msg);
532 JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
534 JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
536 /** \brief Type of the value held by a Value object.
539 nullValue = 0, ///< 'null' value
540 intValue, ///< signed integer value
541 uintValue, ///< unsigned integer value
542 realValue, ///< double value
543 stringValue, ///< UTF-8 string value
544 booleanValue, ///< bool value
545 arrayValue, ///< array value (ordered list)
546 objectValue ///< object value (collection of name/value pairs).
549 enum CommentPlacement {
550 commentBefore = 0, ///< a comment placed on the line before a value
551 commentAfterOnSameLine, ///< a comment just after a value on the same line
552 commentAfter, ///< a comment on the line after a value (only make sense for
554 numberOfCommentPlacement
557 //# ifdef JSON_USE_CPPTL
558 // typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
559 // typedef CppTL::AnyEnumerator<const Value &> EnumValues;
562 /** \brief Lightweight wrapper to tag static string.
564 * Value constructor and objectValue member assignement takes advantage of the
565 * StaticString and avoid the cost of string duplication when storing the
566 * string or the member name.
570 * Json::Value aValue( StaticString("some text") );
571 * Json::Value object;
572 * static const StaticString code("code");
573 * object[code] = 1234;
576 class JSON_API StaticString {
578 explicit StaticString(const char* czstring) : c_str_(czstring) {}
580 operator const char*() const { return c_str_; }
582 const char* c_str() const { return c_str_; }
588 /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
590 * This class is a discriminated union wrapper that can represents a:
591 * - signed integer [range: Value::minInt - Value::maxInt]
592 * - unsigned integer (range: 0 - Value::maxUInt)
597 * - an ordered list of Value
598 * - collection of name/value pairs (javascript object)
600 * The type of the held value is represented by a #ValueType and
601 * can be obtained using type().
603 * Values of an #objectValue or #arrayValue can be accessed using operator[]()
605 * Non-const methods will automatically create the a #nullValue element
606 * if it does not exist.
607 * The sequence of an #arrayValue will be automatically resized and initialized
608 * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
610 * The get() methods can be used to obtain default value in the case the
611 * required element does not exist.
613 * It is possible to iterate over the list of a #objectValue values using
614 * the getMemberNames() method.
616 * \note #Value string-length fit in size_t, but keys must be < 2^30.
617 * (The reason is an implementation detail.) A #CharReader will raise an
618 * exception if a bound is exceeded to avoid security holes in your app,
619 * but the Value API does *not* check bounds. That is the responsibility
622 class JSON_API Value {
623 friend class ValueIteratorBase;
625 typedef std::vector<JSONCPP_STRING> Members;
626 typedef ValueIterator iterator;
627 typedef ValueConstIterator const_iterator;
628 typedef Json::UInt UInt;
629 typedef Json::Int Int;
630 #if defined(JSON_HAS_INT64)
631 typedef Json::UInt64 UInt64;
632 typedef Json::Int64 Int64;
633 #endif // defined(JSON_HAS_INT64)
634 typedef Json::LargestInt LargestInt;
635 typedef Json::LargestUInt LargestUInt;
636 typedef Json::ArrayIndex ArrayIndex;
638 static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
639 static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
640 static Value const& nullSingleton(); ///< Prefer this to null or nullRef.
642 /// Minimum signed integer value that can be stored in a Json::Value.
643 static const LargestInt minLargestInt;
644 /// Maximum signed integer value that can be stored in a Json::Value.
645 static const LargestInt maxLargestInt;
646 /// Maximum unsigned integer value that can be stored in a Json::Value.
647 static const LargestUInt maxLargestUInt;
649 /// Minimum signed int value that can be stored in a Json::Value.
650 static const Int minInt;
651 /// Maximum signed int value that can be stored in a Json::Value.
652 static const Int maxInt;
653 /// Maximum unsigned int value that can be stored in a Json::Value.
654 static const UInt maxUInt;
656 #if defined(JSON_HAS_INT64)
657 /// Minimum signed 64 bits int value that can be stored in a Json::Value.
658 static const Int64 minInt64;
659 /// Maximum signed 64 bits int value that can be stored in a Json::Value.
660 static const Int64 maxInt64;
661 /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
662 static const UInt64 maxUInt64;
663 #endif // defined(JSON_HAS_INT64)
666 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
669 enum DuplicationPolicy {
674 CZString(ArrayIndex index);
675 CZString(char const* str, unsigned length, DuplicationPolicy allocate);
676 CZString(CZString const& other);
677 #if JSON_HAS_RVALUE_REFERENCES
678 CZString(CZString&& other);
681 CZString& operator=(const CZString& other);
683 #if JSON_HAS_RVALUE_REFERENCES
684 CZString& operator=(CZString&& other);
687 bool operator<(CZString const& other) const;
688 bool operator==(CZString const& other) const;
689 ArrayIndex index() const;
690 //const char* c_str() const; ///< \deprecated
691 char const* data() const;
692 unsigned length() const;
693 bool isStaticString() const;
696 void swap(CZString& other);
698 struct StringStorage {
700 unsigned length_: 30; // 1GB max
703 char const* cstr_; // actually, a prefixed string, unless policy is noDup
706 StringStorage storage_;
711 #ifndef JSON_USE_CPPTL_SMALLMAP
712 typedef std::map<CZString, Value> ObjectValues;
714 typedef CppTL::SmallMap<CZString, Value> ObjectValues;
715 #endif // ifndef JSON_USE_CPPTL_SMALLMAP
716 #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
719 /** \brief Create a default Value of the given type.
721 This is a very useful constructor.
722 To create an empty array, pass arrayValue.
723 To create an empty object, pass objectValue.
724 Another Value can then be set to this one by assignment.
725 This is useful since clear() and resize() will not alter types.
729 Json::Value null_value; // null
730 Json::Value arr_value(Json::arrayValue); // []
731 Json::Value obj_value(Json::objectValue); // {}
734 Value(ValueType type = nullValue);
737 #if defined(JSON_HAS_INT64)
740 #endif // if defined(JSON_HAS_INT64)
742 Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
743 Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
744 /** \brief Constructs a value from a static string.
746 * Like other value string constructor but do not duplicate the string for
747 * internal storage. The given string must remain alive after the call to this
749 * \note This works only for null-terminated strings. (We cannot change the
750 * size of this class, so we have nowhere to store the length,
751 * which might be computed later for various operations.)
755 * static StaticString foo("some text");
756 * Json::Value aValue(foo);
759 Value(const StaticString& value);
760 Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
761 #ifdef JSON_USE_CPPTL
762 Value(const CppTL::ConstString& value);
766 Value(const Value& other);
767 #if JSON_HAS_RVALUE_REFERENCES
769 Value(Value&& other);
773 /// Deep copy, then swap(other).
774 /// \note Over-write existing comments. To preserve comments, use #swapPayload().
775 Value& operator=(Value other);
778 void swap(Value& other);
779 /// Swap values but leave comments and source offsets in place.
780 void swapPayload(Value& other);
783 void copy(const Value& other);
784 /// copy values but leave comments and source offsets in place.
785 void copyPayload(const Value& other);
787 ValueType type() const;
789 /// Compare payload only, not comments etc.
790 bool operator<(const Value& other) const;
791 bool operator<=(const Value& other) const;
792 bool operator>=(const Value& other) const;
793 bool operator>(const Value& other) const;
794 bool operator==(const Value& other) const;
795 bool operator!=(const Value& other) const;
796 int compare(const Value& other) const;
798 const char* asCString() const; ///< Embedded zeroes could cause you trouble!
799 #if JSONCPP_USING_SECURE_MEMORY
800 unsigned getCStringLength() const; //Allows you to understand the length of the CString
802 JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
803 /** Get raw char* of string-value.
804 * \return false if !string. (Seg-fault if str or end are NULL.)
807 char const** begin, char const** end) const;
808 #ifdef JSON_USE_CPPTL
809 CppTL::ConstString asConstString() const;
813 #if defined(JSON_HAS_INT64)
814 Int64 asInt64() const;
815 UInt64 asUInt64() const;
816 #endif // if defined(JSON_HAS_INT64)
817 LargestInt asLargestInt() const;
818 LargestUInt asLargestUInt() const;
819 float asFloat() const;
820 double asDouble() const;
826 bool isInt64() const;
828 bool isUInt64() const;
829 bool isIntegral() const;
830 bool isDouble() const;
831 bool isNumeric() const;
832 bool isString() const;
833 bool isArray() const;
834 bool isObject() const;
836 bool isConvertibleTo(ValueType other) const;
838 /// Number of values in array or object
839 ArrayIndex size() const;
841 /// \brief Return true if empty array, empty object, or null;
842 /// otherwise, false.
846 bool operator!() const;
848 /// Remove all object members and array elements.
849 /// \pre type() is arrayValue, objectValue, or nullValue
850 /// \post type() is unchanged
853 /// Resize the array to size elements.
854 /// New elements are initialized to null.
855 /// May only be called on nullValue or arrayValue.
856 /// \pre type() is arrayValue or nullValue
857 /// \post type() is arrayValue
858 void resize(ArrayIndex size);
860 /// Access an array element (zero based index ).
861 /// If the array contains less than index element, then null value are
863 /// in the array so that its size is index+1.
864 /// (You may need to say 'value[0u]' to get your compiler to distinguish
865 /// this from the operator[] which takes a string.)
866 Value& operator[](ArrayIndex index);
868 /// Access an array element (zero based index ).
869 /// If the array contains less than index element, then null value are
871 /// in the array so that its size is index+1.
872 /// (You may need to say 'value[0u]' to get your compiler to distinguish
873 /// this from the operator[] which takes a string.)
874 Value& operator[](int index);
876 /// Access an array element (zero based index )
877 /// (You may need to say 'value[0u]' to get your compiler to distinguish
878 /// this from the operator[] which takes a string.)
879 const Value& operator[](ArrayIndex index) const;
881 /// Access an array element (zero based index )
882 /// (You may need to say 'value[0u]' to get your compiler to distinguish
883 /// this from the operator[] which takes a string.)
884 const Value& operator[](int index) const;
886 /// If the array contains at least index+1 elements, returns the element
888 /// otherwise returns defaultValue.
889 Value get(ArrayIndex index, const Value& defaultValue) const;
890 /// Return true if index < size().
891 bool isValidIndex(ArrayIndex index) const;
892 /// \brief Append value to array at the end.
894 /// Equivalent to jsonvalue[jsonvalue.size()] = value;
895 Value& append(const Value& value);
897 #if JSON_HAS_RVALUE_REFERENCES
898 Value& append(Value&& value);
901 /// Access an object value by name, create a null member if it does not exist.
902 /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
903 /// Exceeding that will cause an exception.
904 Value& operator[](const char* key);
905 /// Access an object value by name, returns null if there is no member with
907 const Value& operator[](const char* key) const;
908 /// Access an object value by name, create a null member if it does not exist.
909 /// \param key may contain embedded nulls.
910 Value& operator[](const JSONCPP_STRING& key);
911 /// Access an object value by name, returns null if there is no member with
913 /// \param key may contain embedded nulls.
914 const Value& operator[](const JSONCPP_STRING& key) const;
915 /** \brief Access an object value by name, create a null member if it does not
918 * If the object has no entry for that name, then the member name used to store
919 * the new entry is not duplicated.
922 * Json::Value object;
923 * static const StaticString code("code");
924 * object[code] = 1234;
927 Value& operator[](const StaticString& key);
928 #ifdef JSON_USE_CPPTL
929 /// Access an object value by name, create a null member if it does not exist.
930 Value& operator[](const CppTL::ConstString& key);
931 /// Access an object value by name, returns null if there is no member with
933 const Value& operator[](const CppTL::ConstString& key) const;
935 /// Return the member named key if it exist, defaultValue otherwise.
937 Value get(const char* key, const Value& defaultValue) const;
938 /// Return the member named key if it exist, defaultValue otherwise.
940 /// \note key may contain embedded nulls.
941 Value get(const char* begin, const char* end, const Value& defaultValue) const;
942 /// Return the member named key if it exist, defaultValue otherwise.
944 /// \param key may contain embedded nulls.
945 Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
946 #ifdef JSON_USE_CPPTL
947 /// Return the member named key if it exist, defaultValue otherwise.
949 Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
951 /// Most general and efficient version of isMember()const, get()const,
952 /// and operator[]const
953 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
954 Value const* find(char const* begin, char const* end) const;
955 /// Most general and efficient version of object-mutators.
956 /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
957 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
958 Value const* demand(char const* begin, char const* end);
959 /// \brief Remove and return the named member.
961 /// Do nothing if it did not exist.
962 /// \return the removed Value, or null.
963 /// \pre type() is objectValue or nullValue
964 /// \post type() is unchanged
966 JSONCPP_DEPRECATED("")
967 Value removeMember(const char* key);
968 /// Same as removeMember(const char*)
969 /// \param key may contain embedded nulls.
971 JSONCPP_DEPRECATED("")
972 Value removeMember(const JSONCPP_STRING& key);
973 /// Same as removeMember(const char* begin, const char* end, Value* removed),
974 /// but 'key' is null-terminated.
975 bool removeMember(const char* key, Value* removed);
976 /** \brief Remove the named map member.
978 Update 'removed' iff removed.
979 \param key may contain embedded nulls.
980 \return true iff removed (no exceptions)
982 bool removeMember(JSONCPP_STRING const& key, Value* removed);
983 /// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
984 bool removeMember(const char* begin, const char* end, Value* removed);
985 /** \brief Remove the indexed array element.
987 O(n) expensive operations.
988 Update 'removed' iff removed.
989 \return true iff removed (no exceptions)
991 bool removeIndex(ArrayIndex i, Value* removed);
993 /// Return true if the object has a member named key.
994 /// \note 'key' must be null-terminated.
995 bool isMember(const char* key) const;
996 /// Return true if the object has a member named key.
997 /// \param key may contain embedded nulls.
998 bool isMember(const JSONCPP_STRING& key) const;
999 /// Same as isMember(JSONCPP_STRING const& key)const
1000 bool isMember(const char* begin, const char* end) const;
1001 #ifdef JSON_USE_CPPTL
1002 /// Return true if the object has a member named key.
1003 bool isMember(const CppTL::ConstString& key) const;
1006 /// \brief Return a list of the member names.
1008 /// If null, return an empty list.
1009 /// \pre type() is objectValue or nullValue
1010 /// \post if type() was nullValue, it remains nullValue
1011 Members getMemberNames() const;
1013 //# ifdef JSON_USE_CPPTL
1014 // EnumMemberNames enumMemberNames() const;
1015 // EnumValues enumValues() const;
1018 /// \deprecated Always pass len.
1019 JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
1020 void setComment(const char* comment, CommentPlacement placement);
1021 /// Comments must be //... or /* ... */
1022 void setComment(const char* comment, size_t len, CommentPlacement placement);
1023 /// Comments must be //... or /* ... */
1024 void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
1025 bool hasComment(CommentPlacement placement) const;
1026 /// Include delimiters and embedded newlines.
1027 JSONCPP_STRING getComment(CommentPlacement placement) const;
1029 JSONCPP_STRING toStyledString() const;
1031 const_iterator begin() const;
1032 const_iterator end() const;
1037 // Accessors for the [start, limit) range of bytes within the JSON text from
1038 // which this value was parsed, if any.
1039 void setOffsetStart(ptrdiff_t start);
1040 void setOffsetLimit(ptrdiff_t limit);
1041 ptrdiff_t getOffsetStart() const;
1042 ptrdiff_t getOffsetLimit() const;
1045 void initBasic(ValueType type, bool allocated = false);
1047 Value& resolveReference(const char* key);
1048 Value& resolveReference(const char* key, const char* end);
1050 struct CommentInfo {
1054 void setComment(const char* text, size_t len);
1059 // struct MemberNamesTransform
1061 // typedef const char *result_type;
1062 // const char *operator()( const CZString &name ) const
1064 // return name.c_str();
1073 char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
1076 ValueType type_ : 8;
1077 unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
1078 // If not allocated_, string_ must be null-terminated.
1079 CommentInfo* comments_;
1081 // [start, limit) byte offsets in the source JSON text from which this Value
1087 /** \brief Experimental and untested: represents an element of the "path" to
1090 class JSON_API PathArgument {
1095 PathArgument(ArrayIndex index);
1096 PathArgument(const char* key);
1097 PathArgument(const JSONCPP_STRING& key);
1105 JSONCPP_STRING key_;
1110 /** \brief Experimental and untested: represents a "path" to access a node.
1113 * - "." => root node
1114 * - ".[n]" => elements at index 'n' of root node (an array value)
1115 * - ".name" => member named 'name' of root node (an object value)
1116 * - ".name1.name2.name3"
1117 * - ".[0][1][2].name1[3]"
1118 * - ".%" => member name is provided as parameter
1119 * - ".[%]" => index is provied as parameter
1121 class JSON_API Path {
1123 Path(const JSONCPP_STRING& path,
1124 const PathArgument& a1 = PathArgument(),
1125 const PathArgument& a2 = PathArgument(),
1126 const PathArgument& a3 = PathArgument(),
1127 const PathArgument& a4 = PathArgument(),
1128 const PathArgument& a5 = PathArgument());
1130 const Value& resolve(const Value& root) const;
1131 Value resolve(const Value& root, const Value& defaultValue) const;
1132 /// Creates the "path" to access the specified node and returns a reference on
1134 Value& make(Value& root) const;
1137 typedef std::vector<const PathArgument*> InArgs;
1138 typedef std::vector<PathArgument> Args;
1140 void makePath(const JSONCPP_STRING& path, const InArgs& in);
1141 void addPathInArg(const JSONCPP_STRING& path,
1143 InArgs::const_iterator& itInArg,
1144 PathArgument::Kind kind);
1145 void invalidPath(const JSONCPP_STRING& path, int location);
1150 /** \brief base class for Value iterators.
1153 class JSON_API ValueIteratorBase {
1155 typedef std::bidirectional_iterator_tag iterator_category;
1156 typedef unsigned int size_t;
1157 typedef int difference_type;
1158 typedef ValueIteratorBase SelfType;
1160 bool operator==(const SelfType& other) const { return isEqual(other); }
1162 bool operator!=(const SelfType& other) const { return !isEqual(other); }
1164 difference_type operator-(const SelfType& other) const {
1165 return other.computeDistance(*this);
1168 /// Return either the index or the member name of the referenced value as a
1172 /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1175 /// Return the member name of the referenced Value, or "" if it is not an
1177 /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1178 JSONCPP_STRING name() const;
1180 /// Return the member name of the referenced Value. "" if it is not an
1182 /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1183 JSONCPP_DEPRECATED("Use `key = name();` instead.")
1184 char const* memberName() const;
1185 /// Return the member name of the referenced Value, or NULL if it is not an
1187 /// \note Better version than memberName(). Allows embedded nulls.
1188 char const* memberName(char const** end) const;
1191 Value& deref() const;
1197 difference_type computeDistance(const SelfType& other) const;
1199 bool isEqual(const SelfType& other) const;
1201 void copy(const SelfType& other);
1204 Value::ObjectValues::iterator current_;
1205 // Indicates that iterator is for a null value.
1209 // For some reason, BORLAND needs these at the end, rather
1210 // than earlier. No idea why.
1211 ValueIteratorBase();
1212 explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
1215 /** \brief const iterator for object and array value.
1218 class JSON_API ValueConstIterator : public ValueIteratorBase {
1222 typedef const Value value_type;
1223 //typedef unsigned int size_t;
1224 //typedef int difference_type;
1225 typedef const Value& reference;
1226 typedef const Value* pointer;
1227 typedef ValueConstIterator SelfType;
1229 ValueConstIterator();
1230 ValueConstIterator(ValueIterator const& other);
1233 /*! \internal Use by Value to create an iterator.
1235 explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
1237 SelfType& operator=(const ValueIteratorBase& other);
1239 SelfType operator++(int) {
1240 SelfType temp(*this);
1245 SelfType operator--(int) {
1246 SelfType temp(*this);
1251 SelfType& operator--() {
1256 SelfType& operator++() {
1261 reference operator*() const { return deref(); }
1263 pointer operator->() const { return &deref(); }
1266 /** \brief Iterator for object and array value.
1268 class JSON_API ValueIterator : public ValueIteratorBase {
1272 typedef Value value_type;
1273 typedef unsigned int size_t;
1274 typedef int difference_type;
1275 typedef Value& reference;
1276 typedef Value* pointer;
1277 typedef ValueIterator SelfType;
1280 explicit ValueIterator(const ValueConstIterator& other);
1281 ValueIterator(const ValueIterator& other);
1284 /*! \internal Use by Value to create an iterator.
1286 explicit ValueIterator(const Value::ObjectValues::iterator& current);
1288 SelfType& operator=(const SelfType& other);
1290 SelfType operator++(int) {
1291 SelfType temp(*this);
1296 SelfType operator--(int) {
1297 SelfType temp(*this);
1302 SelfType& operator--() {
1307 SelfType& operator++() {
1312 reference operator*() const { return deref(); }
1314 pointer operator->() const { return &deref(); }
1321 /// Specialize std::swap() for Json::Value.
1323 inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
1328 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1329 #pragma warning(pop)
1330 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1332 #endif // CPPTL_JSON_H_INCLUDED
1334 // //////////////////////////////////////////////////////////////////////
1335 // End of content of file: include/json/value.h
1336 // //////////////////////////////////////////////////////////////////////
1343 // //////////////////////////////////////////////////////////////////////
1344 // Beginning of content of file: include/json/reader.h
1345 // //////////////////////////////////////////////////////////////////////
1347 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
1348 // Distributed under MIT license, or public domain if desired and
1349 // recognized in your jurisdiction.
1350 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1352 #ifndef CPPTL_JSON_READER_H_INCLUDED
1353 #define CPPTL_JSON_READER_H_INCLUDED
1355 #if !defined(JSON_IS_AMALGAMATION)
1356 #include "features.h"
1358 #endif // if !defined(JSON_IS_AMALGAMATION)
1365 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1367 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1368 #pragma warning(push)
1369 #pragma warning(disable : 4251)
1370 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1372 #pragma pack(push, 8)
1376 /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1379 * \deprecated Use CharReader and CharReaderBuilder.
1381 class JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") JSON_API Reader {
1384 typedef const Char* Location;
1386 /** \brief An error tagged with where in the JSON text it was encountered.
1388 * The offsets give the [start, limit) range of bytes within the text. Note
1389 * that this is bytes, not codepoints.
1392 struct StructuredError {
1393 ptrdiff_t offset_start;
1394 ptrdiff_t offset_limit;
1395 JSONCPP_STRING message;
1398 /** \brief Constructs a Reader allowing all features
1403 /** \brief Constructs a Reader allowing the specified feature set
1406 Reader(const Features& features);
1408 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1410 * \param document UTF-8 encoded string containing the document to read.
1411 * \param root [out] Contains the root value of the document if it was
1412 * successfully parsed.
1413 * \param collectComments \c true to collect comment and allow writing them
1415 * serialization, \c false to discard comments.
1416 * This parameter is ignored if
1417 * Features::allowComments_
1419 * \return \c true if the document was successfully parsed, \c false if an
1423 parse(const std::string& document, Value& root, bool collectComments = true);
1425 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1427 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1429 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1431 * Must be >= beginDoc.
1432 * \param root [out] Contains the root value of the document if it was
1433 * successfully parsed.
1434 * \param collectComments \c true to collect comment and allow writing them
1436 * serialization, \c false to discard comments.
1437 * This parameter is ignored if
1438 Features::allowComments_
1440 * \return \c true if the document was successfully parsed, \c false if an
1443 bool parse(const char* beginDoc,
1446 bool collectComments = true);
1448 /// \brief Parse from input stream.
1449 /// \see Json::operator>>(std::istream&, Json::Value&).
1450 bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true);
1452 /** \brief Returns a user friendly string that list errors in the parsed
1454 * \return Formatted error message with the list of errors with their location
1456 * the parsed document. An empty string is returned if no error
1459 * \deprecated Use getFormattedErrorMessages() instead (typo fix).
1461 JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1462 JSONCPP_STRING getFormatedErrorMessages() const;
1464 /** \brief Returns a user friendly string that list errors in the parsed
1466 * \return Formatted error message with the list of errors with their location
1468 * the parsed document. An empty string is returned if no error
1472 JSONCPP_STRING getFormattedErrorMessages() const;
1474 /** \brief Returns a vector of structured erros encounted while parsing.
1475 * \return A (possibly empty) vector of StructuredError objects. Currently
1476 * only one error can be returned, but the caller should tolerate
1478 * errors. This can occur if the parser recovers from a non-fatal
1479 * parse error and then encounters additional errors.
1481 std::vector<StructuredError> getStructuredErrors() const;
1483 /** \brief Add a semantic error message.
1484 * \param value JSON Value location associated with the error
1485 * \param message The error message.
1486 * \return \c true if the error was successfully added, \c false if the
1487 * Value offset exceeds the document size.
1489 bool pushError(const Value& value, const JSONCPP_STRING& message);
1491 /** \brief Add a semantic error message with extra context.
1492 * \param value JSON Value location associated with the error
1493 * \param message The error message.
1494 * \param extra Additional JSON Value location to contextualize the error
1495 * \return \c true if the error was successfully added, \c false if either
1496 * Value offset exceeds the document size.
1498 bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
1500 /** \brief Return whether there are any errors.
1501 * \return \c true if there are no errors to report \c false if
1502 * errors have occurred.
1508 tokenEndOfStream = 0,
1518 tokenArraySeparator,
1519 tokenMemberSeparator,
1534 JSONCPP_STRING message_;
1538 typedef std::deque<ErrorInfo> Errors;
1540 bool readToken(Token& token);
1542 bool match(Location pattern, int patternLength);
1544 bool readCStyleComment();
1545 bool readCppStyleComment();
1549 bool readObject(Token& token);
1550 bool readArray(Token& token);
1551 bool decodeNumber(Token& token);
1552 bool decodeNumber(Token& token, Value& decoded);
1553 bool decodeString(Token& token);
1554 bool decodeString(Token& token, JSONCPP_STRING& decoded);
1555 bool decodeDouble(Token& token);
1556 bool decodeDouble(Token& token, Value& decoded);
1557 bool decodeUnicodeCodePoint(Token& token,
1560 unsigned int& unicode);
1561 bool decodeUnicodeEscapeSequence(Token& token,
1564 unsigned int& unicode);
1565 bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
1566 bool recoverFromError(TokenType skipUntilToken);
1567 bool addErrorAndRecover(const JSONCPP_STRING& message,
1569 TokenType skipUntilToken);
1570 void skipUntilSpace();
1571 Value& currentValue();
1574 getLocationLineAndColumn(Location location, int& line, int& column) const;
1575 JSONCPP_STRING getLocationLineAndColumn(Location location) const;
1576 void addComment(Location begin, Location end, CommentPlacement placement);
1577 void skipCommentTokens(Token& token);
1579 static bool containsNewLine(Location begin, Location end);
1580 static JSONCPP_STRING normalizeEOL(Location begin, Location end);
1582 typedef std::stack<Value*> Nodes;
1585 JSONCPP_STRING document_;
1589 Location lastValueEnd_;
1591 JSONCPP_STRING commentsBefore_;
1593 bool collectComments_;
1596 /** Interface for reading JSON from a char array.
1598 class JSON_API CharReader {
1600 virtual ~CharReader() {}
1601 /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1603 * The document must be a UTF-8 encoded string containing the document to read.
1605 * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1607 * \param endDoc Pointer on the end of the UTF-8 encoded string of the
1609 * Must be >= beginDoc.
1610 * \param root [out] Contains the root value of the document if it was
1611 * successfully parsed.
1612 * \param errs [out] Formatted error messages (if not NULL)
1613 * a user friendly string that lists errors in the parsed
1615 * \return \c true if the document was successfully parsed, \c false if an
1619 char const* beginDoc, char const* endDoc,
1620 Value* root, JSONCPP_STRING* errs) = 0;
1622 class JSON_API Factory {
1624 virtual ~Factory() {}
1625 /** \brief Allocate a CharReader via operator new().
1626 * \throw std::exception if something goes wrong (e.g. invalid settings)
1628 virtual CharReader* newCharReader() const = 0;
1632 /** \brief Build a CharReader implementation.
1636 using namespace Json;
1637 CharReaderBuilder builder;
1638 builder["collectComments"] = false;
1640 JSONCPP_STRING errs;
1641 bool ok = parseFromStream(builder, std::cin, &value, &errs);
1644 class JSON_API CharReaderBuilder : public CharReader::Factory {
1646 // Note: We use a Json::Value so that we can add data-members to this class
1647 // without a major version bump.
1648 /** Configuration of this builder.
1649 These are case-sensitive.
1650 Available settings (case-sensitive):
1651 - `"collectComments": false or true`
1652 - true to collect comment and allow writing them
1653 back during serialization, false to discard comments.
1654 This parameter is ignored if allowComments is false.
1655 - `"allowComments": false or true`
1656 - true if comments are allowed.
1657 - `"strictRoot": false or true`
1658 - true if root must be either an array or an object value
1659 - `"allowDroppedNullPlaceholders": false or true`
1660 - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1661 - `"allowNumericKeys": false or true`
1662 - true if numeric object keys are allowed.
1663 - `"allowSingleQuotes": false or true`
1664 - true if '' are allowed for strings (both keys and values)
1665 - `"stackLimit": integer`
1666 - Exceeding stackLimit (recursive depth of `readValue()`) will
1668 - This is a security issue (seg-faults caused by deeply nested JSON),
1669 so the default is low.
1670 - `"failIfExtra": false or true`
1671 - If true, `parse()` returns false when extra non-whitespace trails
1672 the JSON value in the input string.
1673 - `"rejectDupKeys": false or true`
1674 - If true, `parse()` returns false when a key is duplicated within an object.
1675 - `"allowSpecialFloats": false or true`
1676 - If true, special float values (NaNs and infinities) are allowed
1677 and their values are lossfree restorable.
1679 You can examine 'settings_` yourself
1680 to see the defaults. You can also write and read them just like any
1684 Json::Value settings_;
1686 CharReaderBuilder();
1687 ~CharReaderBuilder() JSONCPP_OVERRIDE;
1689 CharReader* newCharReader() const JSONCPP_OVERRIDE;
1691 /** \return true if 'settings' are legal and consistent;
1692 * otherwise, indicate bad settings via 'invalid'.
1694 bool validate(Json::Value* invalid) const;
1696 /** A simple way to update a specific setting.
1698 Value& operator[](JSONCPP_STRING key);
1700 /** Called by ctor, but you can use this to reset settings_.
1701 * \pre 'settings' != NULL (but Json::null is fine)
1703 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1705 static void setDefaults(Json::Value* settings);
1706 /** Same as old Features::strictMode().
1707 * \pre 'settings' != NULL (but Json::null is fine)
1709 * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1711 static void strictMode(Json::Value* settings);
1714 /** Consume entire stream and use its begin/end.
1715 * Someday we might have a real StreamReader, but for now this
1718 bool JSON_API parseFromStream(
1719 CharReader::Factory const&,
1721 Value* root, std::string* errs);
1723 /** \brief Read from 'sin' into 'root'.
1725 Always keep comments from the input JSON.
1727 This can be used to read a file into a particular sub-object.
1731 cin >> root["dir"]["file"];
1739 // The input stream JSON would be nested here.
1744 \throw std::exception on parse error.
1745 \see Json::operator<<()
1747 JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
1753 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1754 #pragma warning(pop)
1755 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1757 #endif // CPPTL_JSON_READER_H_INCLUDED
1759 // //////////////////////////////////////////////////////////////////////
1760 // End of content of file: include/json/reader.h
1761 // //////////////////////////////////////////////////////////////////////
1768 // //////////////////////////////////////////////////////////////////////
1769 // Beginning of content of file: include/json/writer.h
1770 // //////////////////////////////////////////////////////////////////////
1772 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
1773 // Distributed under MIT license, or public domain if desired and
1774 // recognized in your jurisdiction.
1775 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1777 #ifndef JSON_WRITER_H_INCLUDED
1778 #define JSON_WRITER_H_INCLUDED
1780 #if !defined(JSON_IS_AMALGAMATION)
1782 #endif // if !defined(JSON_IS_AMALGAMATION)
1787 // Disable warning C4251: <data member>: <type> needs to have dll-interface to
1789 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1790 #pragma warning(push)
1791 #pragma warning(disable : 4251)
1792 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1794 #pragma pack(push, 8)
1804 using namespace Json;
1805 void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1806 std::unique_ptr<StreamWriter> const writer(
1807 factory.newStreamWriter());
1808 writer->write(value, &std::cout);
1809 std::cout << std::endl; // add lf and flush
1813 class JSON_API StreamWriter {
1815 JSONCPP_OSTREAM* sout_; // not owned; will not delete
1818 virtual ~StreamWriter();
1819 /** Write Value into document as configured in sub-class.
1820 Do not take ownership of sout, but maintain a reference during function.
1822 \return zero on success (For now, we always return zero, so check the stream instead.)
1823 \throw std::exception possibly, depending on configuration
1825 virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0;
1827 /** \brief A simple abstract factory.
1829 class JSON_API Factory {
1832 /** \brief Allocate a CharReader via operator new().
1833 * \throw std::exception if something goes wrong (e.g. invalid settings)
1835 virtual StreamWriter* newStreamWriter() const = 0;
1839 /** \brief Write into stringstream, then return string, for convenience.
1840 * A StreamWriter will be created from the factory, used, and then deleted.
1842 JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
1845 /** \brief Build a StreamWriter implementation.
1849 using namespace Json;
1851 StreamWriterBuilder builder;
1852 builder["commentStyle"] = "None";
1853 builder["indentation"] = " "; // or whatever you like
1854 std::unique_ptr<Json::StreamWriter> writer(
1855 builder.newStreamWriter());
1856 writer->write(value, &std::cout);
1857 std::cout << std::endl; // add lf and flush
1860 class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
1862 // Note: We use a Json::Value so that we can add data-members to this class
1863 // without a major version bump.
1864 /** Configuration of this builder.
1865 Available settings (case-sensitive):
1866 - "commentStyle": "None" or "All"
1867 - "indentation": "<anything>"
1868 - "enableYAMLCompatibility": false or true
1869 - slightly change the whitespace around colons
1870 - "dropNullPlaceholders": false or true
1871 - Drop the "null" string from the writer's output for nullValues.
1872 Strictly speaking, this is not valid JSON. But when the output is being
1873 fed to a browser's Javascript, it makes for smaller output and the
1874 browser can handle the output just fine.
1875 - "useSpecialFloats": false or true
1876 - If true, outputs non-finite floating point values in the following way:
1877 NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1880 You can examine 'settings_` yourself
1881 to see the defaults. You can also write and read them just like any
1885 Json::Value settings_;
1887 StreamWriterBuilder();
1888 ~StreamWriterBuilder() JSONCPP_OVERRIDE;
1891 * \throw std::exception if something goes wrong (e.g. invalid settings)
1893 StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE;
1895 /** \return true if 'settings' are legal and consistent;
1896 * otherwise, indicate bad settings via 'invalid'.
1898 bool validate(Json::Value* invalid) const;
1899 /** A simple way to update a specific setting.
1901 Value& operator[](JSONCPP_STRING key);
1903 /** Called by ctor, but you can use this to reset settings_.
1904 * \pre 'settings' != NULL (but Json::null is fine)
1906 * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1908 static void setDefaults(Json::Value* settings);
1911 /** \brief Abstract class for writers.
1912 * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1914 class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer {
1918 virtual JSONCPP_STRING write(const Value& root) = 0;
1921 /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1922 *without formatting (not human friendly).
1924 * The JSON document is written in a single line. It is not intended for 'human'
1926 * but may be usefull to support feature such as RPC where bandwith is limited.
1928 * \deprecated Use StreamWriterBuilder.
1930 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter : public Writer {
1934 ~FastWriter() JSONCPP_OVERRIDE {}
1936 void enableYAMLCompatibility();
1938 /** \brief Drop the "null" string from the writer's output for nullValues.
1939 * Strictly speaking, this is not valid JSON. But when the output is being
1940 * fed to a browser's Javascript, it makes for smaller output and the
1941 * browser can handle the output just fine.
1943 void dropNullPlaceholders();
1945 void omitEndingLineFeed();
1947 public: // overridden from Writer
1948 JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
1951 void writeValue(const Value& value);
1953 JSONCPP_STRING document_;
1954 bool yamlCompatiblityEnabled_;
1955 bool dropNullPlaceholders_;
1956 bool omitEndingLineFeed_;
1959 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1960 *human friendly way.
1962 * The rules for line break and indent are as follow:
1964 * - if empty then print {} without indent and line break
1965 * - if not empty the print '{', line break & indent, print one value per
1967 * and then unindent and line break and print '}'.
1969 * - if empty then print [] without indent and line break
1970 * - if the array contains no object value, empty array or some other value
1972 * and all the values fit on one lines, then print the array on a single
1974 * - otherwise, it the values do not fit on one line, or the array contains
1975 * object or non empty array, then print one value per line.
1977 * If the Value have comments then they are outputed according to their
1980 * \sa Reader, Value, Value::setComment()
1981 * \deprecated Use StreamWriterBuilder.
1983 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter : public Writer {
1986 ~StyledWriter() JSONCPP_OVERRIDE {}
1988 public: // overridden from Writer
1989 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
1990 * \param root Value to serialize.
1991 * \return String containing the JSON document that represents the root value.
1993 JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
1996 void writeValue(const Value& value);
1997 void writeArrayValue(const Value& value);
1998 bool isMultineArray(const Value& value);
1999 void pushValue(const JSONCPP_STRING& value);
2001 void writeWithIndent(const JSONCPP_STRING& value);
2004 void writeCommentBeforeValue(const Value& root);
2005 void writeCommentAfterValueOnSameLine(const Value& root);
2006 bool hasCommentForValue(const Value& value);
2007 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
2009 typedef std::vector<JSONCPP_STRING> ChildValues;
2011 ChildValues childValues_;
2012 JSONCPP_STRING document_;
2013 JSONCPP_STRING indentString_;
2014 unsigned int rightMargin_;
2015 unsigned int indentSize_;
2016 bool addChildValues_;
2019 /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
2021 to a stream rather than to a string.
2023 * The rules for line break and indent are as follow:
2025 * - if empty then print {} without indent and line break
2026 * - if not empty the print '{', line break & indent, print one value per
2028 * and then unindent and line break and print '}'.
2030 * - if empty then print [] without indent and line break
2031 * - if the array contains no object value, empty array or some other value
2033 * and all the values fit on one lines, then print the array on a single
2035 * - otherwise, it the values do not fit on one line, or the array contains
2036 * object or non empty array, then print one value per line.
2038 * If the Value have comments then they are outputed according to their
2041 * \sa Reader, Value, Value::setComment()
2042 * \deprecated Use StreamWriterBuilder.
2044 class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter {
2047 * \param indentation Each level will be indented by this amount extra.
2049 StyledStreamWriter(JSONCPP_STRING indentation = "\t");
2050 ~StyledStreamWriter() {}
2053 /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
2054 * \param out Stream to write to. (Can be ostringstream, e.g.)
2055 * \param root Value to serialize.
2056 * \note There is no point in deriving from Writer, since write() should not
2059 void write(JSONCPP_OSTREAM& out, const Value& root);
2062 void writeValue(const Value& value);
2063 void writeArrayValue(const Value& value);
2064 bool isMultineArray(const Value& value);
2065 void pushValue(const JSONCPP_STRING& value);
2067 void writeWithIndent(const JSONCPP_STRING& value);
2070 void writeCommentBeforeValue(const Value& root);
2071 void writeCommentAfterValueOnSameLine(const Value& root);
2072 bool hasCommentForValue(const Value& value);
2073 static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
2075 typedef std::vector<JSONCPP_STRING> ChildValues;
2077 ChildValues childValues_;
2078 JSONCPP_OSTREAM* document_;
2079 JSONCPP_STRING indentString_;
2080 unsigned int rightMargin_;
2081 JSONCPP_STRING indentation_;
2082 bool addChildValues_ : 1;
2086 #if defined(JSON_HAS_INT64)
2087 JSONCPP_STRING JSON_API valueToString(Int value);
2088 JSONCPP_STRING JSON_API valueToString(UInt value);
2089 #endif // if defined(JSON_HAS_INT64)
2090 JSONCPP_STRING JSON_API valueToString(LargestInt value);
2091 JSONCPP_STRING JSON_API valueToString(LargestUInt value);
2092 JSONCPP_STRING JSON_API valueToString(double value);
2093 JSONCPP_STRING JSON_API valueToString(bool value);
2094 JSONCPP_STRING JSON_API valueToQuotedString(const char* value);
2096 /// \brief Output using the StyledStreamWriter.
2097 /// \see Json::operator>>()
2098 JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
2104 #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2105 #pragma warning(pop)
2106 #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2108 #endif // JSON_WRITER_H_INCLUDED
2110 // //////////////////////////////////////////////////////////////////////
2111 // End of content of file: include/json/writer.h
2112 // //////////////////////////////////////////////////////////////////////
2119 // //////////////////////////////////////////////////////////////////////
2120 // Beginning of content of file: include/json/assertions.h
2121 // //////////////////////////////////////////////////////////////////////
2123 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2124 // Distributed under MIT license, or public domain if desired and
2125 // recognized in your jurisdiction.
2126 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2128 #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
2129 #define CPPTL_JSON_ASSERTIONS_H_INCLUDED
2134 #if !defined(JSON_IS_AMALGAMATION)
2136 #endif // if !defined(JSON_IS_AMALGAMATION)
2138 /** It should not be possible for a maliciously designed file to
2139 * cause an abort() or seg-fault, so these macros are used only
2140 * for pre-condition violations and internal logic errors.
2142 #if JSON_USE_EXCEPTION
2144 // @todo <= add detail about condition in exception
2145 # define JSON_ASSERT(condition) \
2146 {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
2148 # define JSON_FAIL_MESSAGE(message) \
2150 JSONCPP_OSTRINGSTREAM oss; oss << message; \
2151 Json::throwLogicError(oss.str()); \
2155 #else // JSON_USE_EXCEPTION
2157 # define JSON_ASSERT(condition) assert(condition)
2159 // The call to assert() will show the failure message in debug builds. In
2160 // release builds we abort, for a core-dump or debugger.
2161 # define JSON_FAIL_MESSAGE(message) \
2163 JSONCPP_OSTRINGSTREAM oss; oss << message; \
2164 assert(false && oss.str().c_str()); \
2171 #define JSON_ASSERT_MESSAGE(condition, message) \
2172 if (!(condition)) { \
2173 JSON_FAIL_MESSAGE(message); \
2176 #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
2178 // //////////////////////////////////////////////////////////////////////
2179 // End of content of file: include/json/assertions.h
2180 // //////////////////////////////////////////////////////////////////////
2186 #endif //ifndef JSON_AMALGATED_H_INCLUDED