Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/third_party/cpp/json-cpp/include/json/json.h
2868 views
1
/// Json-cpp amalgamated header (http://jsoncpp.sourceforge.net/).
2
/// It is intended to be used with #include "json/json.h"
3
4
// //////////////////////////////////////////////////////////////////////
5
// Beginning of content of file: LICENSE
6
// //////////////////////////////////////////////////////////////////////
7
8
/*
9
The JsonCpp library's source code, including accompanying documentation,
10
tests and demonstration applications, are licensed under the following
11
conditions...
12
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.
16
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).
20
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.
25
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:
28
29
http://en.wikipedia.org/wiki/MIT_License
30
31
The full text of the MIT License follows:
32
33
========================================================================
34
Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
35
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:
43
44
The above copyright notice and this permission notice shall be
45
included in all copies or substantial portions of the Software.
46
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
54
SOFTWARE.
55
========================================================================
56
(END LICENSE TEXT)
57
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
63
license you like.
64
65
*/
66
67
// //////////////////////////////////////////////////////////////////////
68
// End of content of file: LICENSE
69
// //////////////////////////////////////////////////////////////////////
70
71
72
73
74
75
#ifndef JSON_AMALGAMATED_H_INCLUDED
76
# define JSON_AMALGAMATED_H_INCLUDED
77
/// If defined, indicates that the source file is amalgamated
78
/// to prevent private header inclusion.
79
#define JSON_IS_AMALGAMATION
80
81
// //////////////////////////////////////////////////////////////////////
82
// Beginning of content of file: include/json/version.h
83
// //////////////////////////////////////////////////////////////////////
84
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
89
90
# define JSONCPP_VERSION_STRING "1.8.4"
91
# define JSONCPP_VERSION_MAJOR 1
92
# define JSONCPP_VERSION_MINOR 8
93
# define JSONCPP_VERSION_PATCH 4
94
# define JSONCPP_VERSION_QUALIFIER
95
# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
96
97
#ifdef JSONCPP_USING_SECURE_MEMORY
98
#undef JSONCPP_USING_SECURE_MEMORY
99
#endif
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.
103
104
#endif // JSON_VERSION_H_INCLUDED
105
106
// //////////////////////////////////////////////////////////////////////
107
// End of content of file: include/json/version.h
108
// //////////////////////////////////////////////////////////////////////
109
110
111
112
113
114
115
// //////////////////////////////////////////////////////////////////////
116
// Beginning of content of file: include/json/config.h
117
// //////////////////////////////////////////////////////////////////////
118
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
123
124
#ifndef JSON_CONFIG_H_INCLUDED
125
#define JSON_CONFIG_H_INCLUDED
126
#include <stddef.h>
127
#include <string> //typedef String
128
#include <stdint.h> //typedef int64_t, uint64_t
129
130
/// If defined, indicates that json library is embedded in CppTL library.
131
//# define JSON_IN_CPPTL 1
132
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
136
/// std::map
137
/// as Value container.
138
//# define JSON_USE_CPPTL_SMALLMAP 1
139
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
144
#endif
145
146
/// If defined, indicates that the source file is amalgamated
147
/// to prevent private header inclusion.
148
/// Remarks: it is automatically defined in the generated amalgamated header.
149
// #define JSON_IS_AMALGAMATION
150
151
#ifdef JSON_IN_CPPTL
152
#include <cpptl/config.h>
153
#ifndef JSON_USE_CPPTL
154
#define JSON_USE_CPPTL 1
155
#endif
156
#endif
157
158
#ifdef JSON_IN_CPPTL
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)
172
#define JSON_API
173
#endif
174
175
// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
176
// integer
177
// Storages, and 64 bits integer support is disabled.
178
// #define JSON_NO_INT64 1
179
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)
190
# endif // MSVC 6
191
192
# if _MSC_VER >= 1500 // MSVC 2008
193
/// Indicates that the following function is deprecated.
194
# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
195
# endif
196
197
#endif // defined(_MSC_VER)
198
199
// In c++11 the override keyword allows you to explicitly define that a function
200
// is intended to override the base-class version. This makes the code more
201
// manageable 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
# define JSONCPP_OP_EXPLICIT explicit
206
#elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900
207
# define JSONCPP_OVERRIDE override
208
# define JSONCPP_NOEXCEPT throw()
209
# if _MSC_VER >= 1800 // MSVC 2013
210
# define JSONCPP_OP_EXPLICIT explicit
211
# else
212
# define JSONCPP_OP_EXPLICIT
213
# endif
214
#elif defined(_MSC_VER) && _MSC_VER >= 1900
215
# define JSONCPP_OVERRIDE override
216
# define JSONCPP_NOEXCEPT noexcept
217
# define JSONCPP_OP_EXPLICIT explicit
218
#else
219
# define JSONCPP_OVERRIDE
220
# define JSONCPP_NOEXCEPT throw()
221
# define JSONCPP_OP_EXPLICIT
222
#endif
223
224
#ifndef JSON_HAS_RVALUE_REFERENCES
225
226
#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
227
#define JSON_HAS_RVALUE_REFERENCES 1
228
#endif // MSVC >= 2010
229
230
#ifdef __clang__
231
#if __has_feature(cxx_rvalue_references)
232
#define JSON_HAS_RVALUE_REFERENCES 1
233
#endif // has_feature
234
235
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
236
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
237
#define JSON_HAS_RVALUE_REFERENCES 1
238
#endif // GXX_EXPERIMENTAL
239
240
#endif // __clang__ || __GNUC__
241
242
#endif // not defined JSON_HAS_RVALUE_REFERENCES
243
244
#ifndef JSON_HAS_RVALUE_REFERENCES
245
#define JSON_HAS_RVALUE_REFERENCES 0
246
#endif
247
248
#ifdef __clang__
249
# if __has_extension(attribute_deprecated_with_message)
250
# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
251
# endif
252
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
253
# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
254
# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
255
# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
256
# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
257
# endif // GNUC version
258
#endif // __clang__ || __GNUC__
259
260
#if !defined(JSONCPP_DEPRECATED)
261
#define JSONCPP_DEPRECATED(message)
262
#endif // if !defined(JSONCPP_DEPRECATED)
263
264
#if __GNUC__ >= 6
265
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
266
#endif
267
268
#if !defined(JSON_IS_AMALGAMATION)
269
270
# include "version.h"
271
272
# if JSONCPP_USING_SECURE_MEMORY
273
# include "allocator.h" //typedef Allocator
274
# endif
275
276
#endif // if !defined(JSON_IS_AMALGAMATION)
277
278
namespace Json {
279
typedef int Int;
280
typedef unsigned int UInt;
281
#if defined(JSON_NO_INT64)
282
typedef int LargestInt;
283
typedef unsigned int LargestUInt;
284
#undef JSON_HAS_INT64
285
#else // if defined(JSON_NO_INT64)
286
// For Microsoft Visual use specific types as long long is not supported
287
#if defined(_MSC_VER) // Microsoft Visual Studio
288
typedef __int64 Int64;
289
typedef unsigned __int64 UInt64;
290
#else // if defined(_MSC_VER) // Other platforms, use long long
291
typedef int64_t Int64;
292
typedef uint64_t UInt64;
293
#endif // if defined(_MSC_VER)
294
typedef Int64 LargestInt;
295
typedef UInt64 LargestUInt;
296
#define JSON_HAS_INT64
297
#endif // if defined(JSON_NO_INT64)
298
#if JSONCPP_USING_SECURE_MEMORY
299
#define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
300
#define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
301
#define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
302
#define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
303
#define JSONCPP_ISTREAM std::istream
304
#else
305
#define JSONCPP_STRING std::string
306
#define JSONCPP_OSTRINGSTREAM std::ostringstream
307
#define JSONCPP_OSTREAM std::ostream
308
#define JSONCPP_ISTRINGSTREAM std::istringstream
309
#define JSONCPP_ISTREAM std::istream
310
#endif // if JSONCPP_USING_SECURE_MEMORY
311
} // end namespace Json
312
313
#endif // JSON_CONFIG_H_INCLUDED
314
315
// //////////////////////////////////////////////////////////////////////
316
// End of content of file: include/json/config.h
317
// //////////////////////////////////////////////////////////////////////
318
319
320
321
322
323
324
// //////////////////////////////////////////////////////////////////////
325
// Beginning of content of file: include/json/forwards.h
326
// //////////////////////////////////////////////////////////////////////
327
328
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
329
// Distributed under MIT license, or public domain if desired and
330
// recognized in your jurisdiction.
331
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
332
333
#ifndef JSON_FORWARDS_H_INCLUDED
334
#define JSON_FORWARDS_H_INCLUDED
335
336
#if !defined(JSON_IS_AMALGAMATION)
337
#include "config.h"
338
#endif // if !defined(JSON_IS_AMALGAMATION)
339
340
namespace Json {
341
342
// writer.h
343
class FastWriter;
344
class StyledWriter;
345
346
// reader.h
347
class Reader;
348
349
// features.h
350
class Features;
351
352
// value.h
353
typedef unsigned int ArrayIndex;
354
class StaticString;
355
class Path;
356
class PathArgument;
357
class Value;
358
class ValueIteratorBase;
359
class ValueIterator;
360
class ValueConstIterator;
361
362
} // namespace Json
363
364
#endif // JSON_FORWARDS_H_INCLUDED
365
366
// //////////////////////////////////////////////////////////////////////
367
// End of content of file: include/json/forwards.h
368
// //////////////////////////////////////////////////////////////////////
369
370
371
372
373
374
375
// //////////////////////////////////////////////////////////////////////
376
// Beginning of content of file: include/json/features.h
377
// //////////////////////////////////////////////////////////////////////
378
379
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
380
// Distributed under MIT license, or public domain if desired and
381
// recognized in your jurisdiction.
382
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
383
384
#ifndef CPPTL_JSON_FEATURES_H_INCLUDED
385
#define CPPTL_JSON_FEATURES_H_INCLUDED
386
387
#if !defined(JSON_IS_AMALGAMATION)
388
#include "forwards.h"
389
#endif // if !defined(JSON_IS_AMALGAMATION)
390
391
#pragma pack(push, 8)
392
393
namespace Json {
394
395
/** \brief Configuration passed to reader and writer.
396
* This configuration object can be used to force the Reader or Writer
397
* to behave in a standard conforming way.
398
*/
399
class JSON_API Features {
400
public:
401
/** \brief A configuration that allows all features and assumes all strings
402
* are UTF-8.
403
* - C & C++ comments are allowed
404
* - Root object can be any JSON value
405
* - Assumes Value strings are encoded in UTF-8
406
*/
407
static Features all();
408
409
/** \brief A configuration that is strictly compatible with the JSON
410
* specification.
411
* - Comments are forbidden.
412
* - Root object must be either an array or an object value.
413
* - Assumes Value strings are encoded in UTF-8
414
*/
415
static Features strictMode();
416
417
/** \brief Initialize the configuration like JsonConfig::allFeatures;
418
*/
419
Features();
420
421
/// \c true if comments are allowed. Default: \c true.
422
bool allowComments_;
423
424
/// \c true if root must be either an array or an object value. Default: \c
425
/// false.
426
bool strictRoot_;
427
428
/// \c true if dropped null placeholders are allowed. Default: \c false.
429
bool allowDroppedNullPlaceholders_;
430
431
/// \c true if numeric object key are allowed. Default: \c false.
432
bool allowNumericKeys_;
433
};
434
435
} // namespace Json
436
437
#pragma pack(pop)
438
439
#endif // CPPTL_JSON_FEATURES_H_INCLUDED
440
441
// //////////////////////////////////////////////////////////////////////
442
// End of content of file: include/json/features.h
443
// //////////////////////////////////////////////////////////////////////
444
445
446
447
448
449
450
// //////////////////////////////////////////////////////////////////////
451
// Beginning of content of file: include/json/value.h
452
// //////////////////////////////////////////////////////////////////////
453
454
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
455
// Distributed under MIT license, or public domain if desired and
456
// recognized in your jurisdiction.
457
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
458
459
#ifndef CPPTL_JSON_H_INCLUDED
460
#define CPPTL_JSON_H_INCLUDED
461
462
#if !defined(JSON_IS_AMALGAMATION)
463
#include "forwards.h"
464
#endif // if !defined(JSON_IS_AMALGAMATION)
465
#include <string>
466
#include <vector>
467
#include <exception>
468
469
#ifndef JSON_USE_CPPTL_SMALLMAP
470
#include <map>
471
#else
472
#include <cpptl/smallmap.h>
473
#endif
474
#ifdef JSON_USE_CPPTL
475
#include <cpptl/forwards.h>
476
#endif
477
478
//Conditional NORETURN attribute on the throw functions would:
479
// a) suppress false positives from static code analysis
480
// b) possibly improve optimization opportunities.
481
#if !defined(JSONCPP_NORETURN)
482
# if defined(_MSC_VER)
483
# define JSONCPP_NORETURN __declspec(noreturn)
484
# elif defined(__GNUC__)
485
# define JSONCPP_NORETURN __attribute__ ((__noreturn__))
486
# else
487
# define JSONCPP_NORETURN
488
# endif
489
#endif
490
491
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
492
// be used by...
493
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
494
#pragma warning(push)
495
#pragma warning(disable : 4251)
496
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
497
498
#pragma pack(push, 8)
499
500
/** \brief JSON (JavaScript Object Notation).
501
*/
502
namespace Json {
503
504
/** Base class for all exceptions we throw.
505
*
506
* We use nothing but these internally. Of course, STL can throw others.
507
*/
508
class JSON_API Exception : public std::exception {
509
public:
510
Exception(JSONCPP_STRING const& msg);
511
~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
512
char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
513
protected:
514
JSONCPP_STRING msg_;
515
};
516
517
/** Exceptions which the user cannot easily avoid.
518
*
519
* E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
520
*
521
* \remark derived from Json::Exception
522
*/
523
class JSON_API RuntimeError : public Exception {
524
public:
525
RuntimeError(JSONCPP_STRING const& msg);
526
};
527
528
/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
529
*
530
* These are precondition-violations (user bugs) and internal errors (our bugs).
531
*
532
* \remark derived from Json::Exception
533
*/
534
class JSON_API LogicError : public Exception {
535
public:
536
LogicError(JSONCPP_STRING const& msg);
537
};
538
539
/// used internally
540
JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
541
/// used internally
542
JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
543
544
/** \brief Type of the value held by a Value object.
545
*/
546
enum ValueType {
547
nullValue = 0, ///< 'null' value
548
intValue, ///< signed integer value
549
uintValue, ///< unsigned integer value
550
realValue, ///< double value
551
stringValue, ///< UTF-8 string value
552
booleanValue, ///< bool value
553
arrayValue, ///< array value (ordered list)
554
objectValue ///< object value (collection of name/value pairs).
555
};
556
557
enum CommentPlacement {
558
commentBefore = 0, ///< a comment placed on the line before a value
559
commentAfterOnSameLine, ///< a comment just after a value on the same line
560
commentAfter, ///< a comment on the line after a value (only make sense for
561
/// root value)
562
numberOfCommentPlacement
563
};
564
565
/** \brief Type of precision for formatting of real values.
566
*/
567
enum PrecisionType {
568
significantDigits = 0, ///< we set max number of significant digits in string
569
decimalPlaces ///< we set max number of digits after "." in string
570
};
571
572
//# ifdef JSON_USE_CPPTL
573
// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
574
// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
575
//# endif
576
577
/** \brief Lightweight wrapper to tag static string.
578
*
579
* Value constructor and objectValue member assignment takes advantage of the
580
* StaticString and avoid the cost of string duplication when storing the
581
* string or the member name.
582
*
583
* Example of usage:
584
* \code
585
* Json::Value aValue( StaticString("some text") );
586
* Json::Value object;
587
* static const StaticString code("code");
588
* object[code] = 1234;
589
* \endcode
590
*/
591
class JSON_API StaticString {
592
public:
593
explicit StaticString(const char* czstring) : c_str_(czstring) {}
594
595
operator const char*() const { return c_str_; }
596
597
const char* c_str() const { return c_str_; }
598
599
private:
600
const char* c_str_;
601
};
602
603
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
604
*
605
* This class is a discriminated union wrapper that can represents a:
606
* - signed integer [range: Value::minInt - Value::maxInt]
607
* - unsigned integer (range: 0 - Value::maxUInt)
608
* - double
609
* - UTF-8 string
610
* - boolean
611
* - 'null'
612
* - an ordered list of Value
613
* - collection of name/value pairs (javascript object)
614
*
615
* The type of the held value is represented by a #ValueType and
616
* can be obtained using type().
617
*
618
* Values of an #objectValue or #arrayValue can be accessed using operator[]()
619
* methods.
620
* Non-const methods will automatically create the a #nullValue element
621
* if it does not exist.
622
* The sequence of an #arrayValue will be automatically resized and initialized
623
* with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
624
*
625
* The get() methods can be used to obtain default value in the case the
626
* required element does not exist.
627
*
628
* It is possible to iterate over the list of a #objectValue values using
629
* the getMemberNames() method.
630
*
631
* \note #Value string-length fit in size_t, but keys must be < 2^30.
632
* (The reason is an implementation detail.) A #CharReader will raise an
633
* exception if a bound is exceeded to avoid security holes in your app,
634
* but the Value API does *not* check bounds. That is the responsibility
635
* of the caller.
636
*/
637
class JSON_API Value {
638
friend class ValueIteratorBase;
639
public:
640
typedef std::vector<JSONCPP_STRING> Members;
641
typedef ValueIterator iterator;
642
typedef ValueConstIterator const_iterator;
643
typedef Json::UInt UInt;
644
typedef Json::Int Int;
645
#if defined(JSON_HAS_INT64)
646
typedef Json::UInt64 UInt64;
647
typedef Json::Int64 Int64;
648
#endif // defined(JSON_HAS_INT64)
649
typedef Json::LargestInt LargestInt;
650
typedef Json::LargestUInt LargestUInt;
651
typedef Json::ArrayIndex ArrayIndex;
652
653
// Required for boost integration, e. g. BOOST_TEST
654
typedef std::string value_type;
655
656
static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
657
static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
658
static Value const& nullSingleton(); ///< Prefer this to null or nullRef.
659
660
/// Minimum signed integer value that can be stored in a Json::Value.
661
static const LargestInt minLargestInt;
662
/// Maximum signed integer value that can be stored in a Json::Value.
663
static const LargestInt maxLargestInt;
664
/// Maximum unsigned integer value that can be stored in a Json::Value.
665
static const LargestUInt maxLargestUInt;
666
667
/// Minimum signed int value that can be stored in a Json::Value.
668
static const Int minInt;
669
/// Maximum signed int value that can be stored in a Json::Value.
670
static const Int maxInt;
671
/// Maximum unsigned int value that can be stored in a Json::Value.
672
static const UInt maxUInt;
673
674
#if defined(JSON_HAS_INT64)
675
/// Minimum signed 64 bits int value that can be stored in a Json::Value.
676
static const Int64 minInt64;
677
/// Maximum signed 64 bits int value that can be stored in a Json::Value.
678
static const Int64 maxInt64;
679
/// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
680
static const UInt64 maxUInt64;
681
#endif // defined(JSON_HAS_INT64)
682
683
/// Default precision for real value for string representation.
684
static const UInt defaultRealPrecision;
685
686
// Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
687
// when using gcc and clang backend compilers. CZString
688
// cannot be defined as private. See issue #486
689
#ifdef __NVCC__
690
public:
691
#else
692
private:
693
#endif
694
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
695
class CZString {
696
public:
697
enum DuplicationPolicy {
698
noDuplication = 0,
699
duplicate,
700
duplicateOnCopy
701
};
702
CZString(ArrayIndex index);
703
CZString(char const* str, unsigned length, DuplicationPolicy allocate);
704
CZString(CZString const& other);
705
#if JSON_HAS_RVALUE_REFERENCES
706
CZString(CZString&& other);
707
#endif
708
~CZString();
709
CZString& operator=(const CZString& other);
710
711
#if JSON_HAS_RVALUE_REFERENCES
712
CZString& operator=(CZString&& other);
713
#endif
714
715
bool operator<(CZString const& other) const;
716
bool operator==(CZString const& other) const;
717
ArrayIndex index() const;
718
//const char* c_str() const; ///< \deprecated
719
char const* data() const;
720
unsigned length() const;
721
bool isStaticString() const;
722
723
private:
724
void swap(CZString& other);
725
726
struct StringStorage {
727
unsigned policy_: 2;
728
unsigned length_: 30; // 1GB max
729
};
730
731
char const* cstr_; // actually, a prefixed string, unless policy is noDup
732
union {
733
ArrayIndex index_;
734
StringStorage storage_;
735
};
736
};
737
738
public:
739
#ifndef JSON_USE_CPPTL_SMALLMAP
740
typedef std::map<CZString, Value> ObjectValues;
741
#else
742
typedef CppTL::SmallMap<CZString, Value> ObjectValues;
743
#endif // ifndef JSON_USE_CPPTL_SMALLMAP
744
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
745
746
public:
747
/** \brief Create a default Value of the given type.
748
749
This is a very useful constructor.
750
To create an empty array, pass arrayValue.
751
To create an empty object, pass objectValue.
752
Another Value can then be set to this one by assignment.
753
This is useful since clear() and resize() will not alter types.
754
755
Examples:
756
\code
757
Json::Value null_value; // null
758
Json::Value arr_value(Json::arrayValue); // []
759
Json::Value obj_value(Json::objectValue); // {}
760
\endcode
761
*/
762
Value(ValueType type = nullValue);
763
Value(Int value);
764
Value(UInt value);
765
#if defined(JSON_HAS_INT64)
766
Value(Int64 value);
767
Value(UInt64 value);
768
#endif // if defined(JSON_HAS_INT64)
769
Value(double value);
770
Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
771
Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
772
/** \brief Constructs a value from a static string.
773
774
* Like other value string constructor but do not duplicate the string for
775
* internal storage. The given string must remain alive after the call to this
776
* constructor.
777
* \note This works only for null-terminated strings. (We cannot change the
778
* size of this class, so we have nowhere to store the length,
779
* which might be computed later for various operations.)
780
*
781
* Example of usage:
782
* \code
783
* static StaticString foo("some text");
784
* Json::Value aValue(foo);
785
* \endcode
786
*/
787
Value(const StaticString& value);
788
Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
789
#ifdef JSON_USE_CPPTL
790
Value(const CppTL::ConstString& value);
791
#endif
792
Value(bool value);
793
/// Deep copy.
794
Value(const Value& other);
795
#if JSON_HAS_RVALUE_REFERENCES
796
/// Move constructor
797
Value(Value&& other);
798
#endif
799
~Value();
800
801
/// Deep copy, then swap(other).
802
/// \note Over-write existing comments. To preserve comments, use #swapPayload().
803
Value& operator=(Value other);
804
805
/// Swap everything.
806
void swap(Value& other);
807
/// Swap values but leave comments and source offsets in place.
808
void swapPayload(Value& other);
809
810
/// copy everything.
811
void copy(const Value& other);
812
/// copy values but leave comments and source offsets in place.
813
void copyPayload(const Value& other);
814
815
ValueType type() const;
816
817
/// Compare payload only, not comments etc.
818
bool operator<(const Value& other) const;
819
bool operator<=(const Value& other) const;
820
bool operator>=(const Value& other) const;
821
bool operator>(const Value& other) const;
822
bool operator==(const Value& other) const;
823
bool operator!=(const Value& other) const;
824
int compare(const Value& other) const;
825
826
const char* asCString() const; ///< Embedded zeroes could cause you trouble!
827
#if JSONCPP_USING_SECURE_MEMORY
828
unsigned getCStringLength() const; //Allows you to understand the length of the CString
829
#endif
830
JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
831
/** Get raw char* of string-value.
832
* \return false if !string. (Seg-fault if str or end are NULL.)
833
*/
834
bool getString(
835
char const** begin, char const** end) const;
836
#ifdef JSON_USE_CPPTL
837
CppTL::ConstString asConstString() const;
838
#endif
839
Int asInt() const;
840
UInt asUInt() const;
841
#if defined(JSON_HAS_INT64)
842
Int64 asInt64() const;
843
UInt64 asUInt64() const;
844
#endif // if defined(JSON_HAS_INT64)
845
LargestInt asLargestInt() const;
846
LargestUInt asLargestUInt() const;
847
float asFloat() const;
848
double asDouble() const;
849
bool asBool() const;
850
851
bool isNull() const;
852
bool isBool() const;
853
bool isInt() const;
854
bool isInt64() const;
855
bool isUInt() const;
856
bool isUInt64() const;
857
bool isIntegral() const;
858
bool isDouble() const;
859
bool isNumeric() const;
860
bool isString() const;
861
bool isArray() const;
862
bool isObject() const;
863
864
bool isConvertibleTo(ValueType other) const;
865
866
/// Number of values in array or object
867
ArrayIndex size() const;
868
869
/// \brief Return true if empty array, empty object, or null;
870
/// otherwise, false.
871
bool empty() const;
872
873
/// Return !isNull()
874
JSONCPP_OP_EXPLICIT operator bool() const;
875
876
/// Remove all object members and array elements.
877
/// \pre type() is arrayValue, objectValue, or nullValue
878
/// \post type() is unchanged
879
void clear();
880
881
/// Resize the array to size elements.
882
/// New elements are initialized to null.
883
/// May only be called on nullValue or arrayValue.
884
/// \pre type() is arrayValue or nullValue
885
/// \post type() is arrayValue
886
void resize(ArrayIndex size);
887
888
/// Access an array element (zero based index ).
889
/// If the array contains less than index element, then null value are
890
/// inserted
891
/// in the array so that its size is index+1.
892
/// (You may need to say 'value[0u]' to get your compiler to distinguish
893
/// this from the operator[] which takes a string.)
894
Value& operator[](ArrayIndex index);
895
896
/// Access an array element (zero based index ).
897
/// If the array contains less than index element, then null value are
898
/// inserted
899
/// in the array so that its size is index+1.
900
/// (You may need to say 'value[0u]' to get your compiler to distinguish
901
/// this from the operator[] which takes a string.)
902
Value& operator[](int index);
903
904
/// Access an array element (zero based index )
905
/// (You may need to say 'value[0u]' to get your compiler to distinguish
906
/// this from the operator[] which takes a string.)
907
const Value& operator[](ArrayIndex index) const;
908
909
/// Access an array element (zero based index )
910
/// (You may need to say 'value[0u]' to get your compiler to distinguish
911
/// this from the operator[] which takes a string.)
912
const Value& operator[](int index) const;
913
914
/// If the array contains at least index+1 elements, returns the element
915
/// value,
916
/// otherwise returns defaultValue.
917
Value get(ArrayIndex index, const Value& defaultValue) const;
918
/// Return true if index < size().
919
bool isValidIndex(ArrayIndex index) const;
920
/// \brief Append value to array at the end.
921
///
922
/// Equivalent to jsonvalue[jsonvalue.size()] = value;
923
Value& append(const Value& value);
924
925
#if JSON_HAS_RVALUE_REFERENCES
926
Value& append(Value&& value);
927
#endif
928
929
/// Access an object value by name, create a null member if it does not exist.
930
/// \note Because of our implementation, keys are limited to 2^30 -1 chars.
931
/// Exceeding that will cause an exception.
932
Value& operator[](const char* key);
933
/// Access an object value by name, returns null if there is no member with
934
/// that name.
935
const Value& operator[](const char* key) const;
936
/// Access an object value by name, create a null member if it does not exist.
937
/// \param key may contain embedded nulls.
938
Value& operator[](const JSONCPP_STRING& key);
939
/// Access an object value by name, returns null if there is no member with
940
/// that name.
941
/// \param key may contain embedded nulls.
942
const Value& operator[](const JSONCPP_STRING& key) const;
943
/** \brief Access an object value by name, create a null member if it does not
944
exist.
945
946
* If the object has no entry for that name, then the member name used to store
947
* the new entry is not duplicated.
948
* Example of use:
949
* \code
950
* Json::Value object;
951
* static const StaticString code("code");
952
* object[code] = 1234;
953
* \endcode
954
*/
955
Value& operator[](const StaticString& key);
956
#ifdef JSON_USE_CPPTL
957
/// Access an object value by name, create a null member if it does not exist.
958
Value& operator[](const CppTL::ConstString& key);
959
/// Access an object value by name, returns null if there is no member with
960
/// that name.
961
const Value& operator[](const CppTL::ConstString& key) const;
962
#endif
963
/// Return the member named key if it exist, defaultValue otherwise.
964
/// \note deep copy
965
Value get(const char* key, const Value& defaultValue) const;
966
/// Return the member named key if it exist, defaultValue otherwise.
967
/// \note deep copy
968
/// \note key may contain embedded nulls.
969
Value get(const char* begin, const char* end, const Value& defaultValue) const;
970
/// Return the member named key if it exist, defaultValue otherwise.
971
/// \note deep copy
972
/// \param key may contain embedded nulls.
973
Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
974
#ifdef JSON_USE_CPPTL
975
/// Return the member named key if it exist, defaultValue otherwise.
976
/// \note deep copy
977
Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
978
#endif
979
/// Most general and efficient version of isMember()const, get()const,
980
/// and operator[]const
981
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
982
Value const* find(char const* begin, char const* end) const;
983
/// Most general and efficient version of object-mutators.
984
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
985
/// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
986
Value const* demand(char const* begin, char const* end);
987
/// \brief Remove and return the named member.
988
///
989
/// Do nothing if it did not exist.
990
/// \return the removed Value, or null.
991
/// \pre type() is objectValue or nullValue
992
/// \post type() is unchanged
993
/// \deprecated
994
void removeMember(const char* key);
995
/// Same as removeMember(const char*)
996
/// \param key may contain embedded nulls.
997
/// \deprecated
998
void removeMember(const JSONCPP_STRING& key);
999
/// Same as removeMember(const char* begin, const char* end, Value* removed),
1000
/// but 'key' is null-terminated.
1001
bool removeMember(const char* key, Value* removed);
1002
/** \brief Remove the named map member.
1003
1004
Update 'removed' iff removed.
1005
\param key may contain embedded nulls.
1006
\return true iff removed (no exceptions)
1007
*/
1008
bool removeMember(JSONCPP_STRING const& key, Value* removed);
1009
/// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
1010
bool removeMember(const char* begin, const char* end, Value* removed);
1011
/** \brief Remove the indexed array element.
1012
1013
O(n) expensive operations.
1014
Update 'removed' iff removed.
1015
\return true iff removed (no exceptions)
1016
*/
1017
bool removeIndex(ArrayIndex i, Value* removed);
1018
1019
/// Return true if the object has a member named key.
1020
/// \note 'key' must be null-terminated.
1021
bool isMember(const char* key) const;
1022
/// Return true if the object has a member named key.
1023
/// \param key may contain embedded nulls.
1024
bool isMember(const JSONCPP_STRING& key) const;
1025
/// Same as isMember(JSONCPP_STRING const& key)const
1026
bool isMember(const char* begin, const char* end) const;
1027
#ifdef JSON_USE_CPPTL
1028
/// Return true if the object has a member named key.
1029
bool isMember(const CppTL::ConstString& key) const;
1030
#endif
1031
1032
/// \brief Return a list of the member names.
1033
///
1034
/// If null, return an empty list.
1035
/// \pre type() is objectValue or nullValue
1036
/// \post if type() was nullValue, it remains nullValue
1037
Members getMemberNames() const;
1038
1039
//# ifdef JSON_USE_CPPTL
1040
// EnumMemberNames enumMemberNames() const;
1041
// EnumValues enumValues() const;
1042
//# endif
1043
1044
/// \deprecated Always pass len.
1045
JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
1046
void setComment(const char* comment, CommentPlacement placement);
1047
/// Comments must be //... or /* ... */
1048
void setComment(const char* comment, size_t len, CommentPlacement placement);
1049
/// Comments must be //... or /* ... */
1050
void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
1051
bool hasComment(CommentPlacement placement) const;
1052
/// Include delimiters and embedded newlines.
1053
JSONCPP_STRING getComment(CommentPlacement placement) const;
1054
1055
JSONCPP_STRING toStyledString() const;
1056
1057
const_iterator begin() const;
1058
const_iterator end() const;
1059
1060
iterator begin();
1061
iterator end();
1062
1063
// Accessors for the [start, limit) range of bytes within the JSON text from
1064
// which this value was parsed, if any.
1065
void setOffsetStart(ptrdiff_t start);
1066
void setOffsetLimit(ptrdiff_t limit);
1067
ptrdiff_t getOffsetStart() const;
1068
ptrdiff_t getOffsetLimit() const;
1069
1070
private:
1071
void initBasic(ValueType type, bool allocated = false);
1072
void dupPayload(const Value& other);
1073
void releasePayload();
1074
void dupMeta(const Value& other);
1075
1076
Value& resolveReference(const char* key);
1077
Value& resolveReference(const char* key, const char* end);
1078
1079
struct CommentInfo {
1080
CommentInfo();
1081
~CommentInfo();
1082
1083
void setComment(const char* text, size_t len);
1084
1085
char* comment_;
1086
};
1087
1088
// struct MemberNamesTransform
1089
//{
1090
// typedef const char *result_type;
1091
// const char *operator()( const CZString &name ) const
1092
// {
1093
// return name.c_str();
1094
// }
1095
//};
1096
1097
union ValueHolder {
1098
LargestInt int_;
1099
LargestUInt uint_;
1100
double real_;
1101
bool bool_;
1102
char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
1103
ObjectValues* map_;
1104
} value_;
1105
ValueType type_ : 8;
1106
unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
1107
// If not allocated_, string_ must be null-terminated.
1108
CommentInfo* comments_;
1109
1110
// [start, limit) byte offsets in the source JSON text from which this Value
1111
// was extracted.
1112
ptrdiff_t start_;
1113
ptrdiff_t limit_;
1114
};
1115
1116
/** \brief Experimental and untested: represents an element of the "path" to
1117
* access a node.
1118
*/
1119
class JSON_API PathArgument {
1120
public:
1121
friend class Path;
1122
1123
PathArgument();
1124
PathArgument(ArrayIndex index);
1125
PathArgument(const char* key);
1126
PathArgument(const JSONCPP_STRING& key);
1127
1128
private:
1129
enum Kind {
1130
kindNone = 0,
1131
kindIndex,
1132
kindKey
1133
};
1134
JSONCPP_STRING key_;
1135
ArrayIndex index_;
1136
Kind kind_;
1137
};
1138
1139
/** \brief Experimental and untested: represents a "path" to access a node.
1140
*
1141
* Syntax:
1142
* - "." => root node
1143
* - ".[n]" => elements at index 'n' of root node (an array value)
1144
* - ".name" => member named 'name' of root node (an object value)
1145
* - ".name1.name2.name3"
1146
* - ".[0][1][2].name1[3]"
1147
* - ".%" => member name is provided as parameter
1148
* - ".[%]" => index is provied as parameter
1149
*/
1150
class JSON_API Path {
1151
public:
1152
Path(const JSONCPP_STRING& path,
1153
const PathArgument& a1 = PathArgument(),
1154
const PathArgument& a2 = PathArgument(),
1155
const PathArgument& a3 = PathArgument(),
1156
const PathArgument& a4 = PathArgument(),
1157
const PathArgument& a5 = PathArgument());
1158
1159
const Value& resolve(const Value& root) const;
1160
Value resolve(const Value& root, const Value& defaultValue) const;
1161
/// Creates the "path" to access the specified node and returns a reference on
1162
/// the node.
1163
Value& make(Value& root) const;
1164
1165
private:
1166
typedef std::vector<const PathArgument*> InArgs;
1167
typedef std::vector<PathArgument> Args;
1168
1169
void makePath(const JSONCPP_STRING& path, const InArgs& in);
1170
void addPathInArg(const JSONCPP_STRING& path,
1171
const InArgs& in,
1172
InArgs::const_iterator& itInArg,
1173
PathArgument::Kind kind);
1174
void invalidPath(const JSONCPP_STRING& path, int location);
1175
1176
Args args_;
1177
};
1178
1179
/** \brief base class for Value iterators.
1180
*
1181
*/
1182
class JSON_API ValueIteratorBase {
1183
public:
1184
typedef std::bidirectional_iterator_tag iterator_category;
1185
typedef unsigned int size_t;
1186
typedef int difference_type;
1187
typedef ValueIteratorBase SelfType;
1188
1189
bool operator==(const SelfType& other) const { return isEqual(other); }
1190
1191
bool operator!=(const SelfType& other) const { return !isEqual(other); }
1192
1193
difference_type operator-(const SelfType& other) const {
1194
return other.computeDistance(*this);
1195
}
1196
1197
/// Return either the index or the member name of the referenced value as a
1198
/// Value.
1199
Value key() const;
1200
1201
/// Return the index of the referenced Value, or -1 if it is not an arrayValue.
1202
UInt index() const;
1203
1204
/// Return the member name of the referenced Value, or "" if it is not an
1205
/// objectValue.
1206
/// \note Avoid `c_str()` on result, as embedded zeroes are possible.
1207
JSONCPP_STRING name() const;
1208
1209
/// Return the member name of the referenced Value. "" if it is not an
1210
/// objectValue.
1211
/// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
1212
JSONCPP_DEPRECATED("Use `key = name();` instead.")
1213
char const* memberName() const;
1214
/// Return the member name of the referenced Value, or NULL if it is not an
1215
/// objectValue.
1216
/// \note Better version than memberName(). Allows embedded nulls.
1217
char const* memberName(char const** end) const;
1218
1219
protected:
1220
Value& deref() const;
1221
1222
void increment();
1223
1224
void decrement();
1225
1226
difference_type computeDistance(const SelfType& other) const;
1227
1228
bool isEqual(const SelfType& other) const;
1229
1230
void copy(const SelfType& other);
1231
1232
private:
1233
Value::ObjectValues::iterator current_;
1234
// Indicates that iterator is for a null value.
1235
bool isNull_;
1236
1237
public:
1238
// For some reason, BORLAND needs these at the end, rather
1239
// than earlier. No idea why.
1240
ValueIteratorBase();
1241
explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
1242
};
1243
1244
/** \brief const iterator for object and array value.
1245
*
1246
*/
1247
class JSON_API ValueConstIterator : public ValueIteratorBase {
1248
friend class Value;
1249
1250
public:
1251
typedef const Value value_type;
1252
//typedef unsigned int size_t;
1253
//typedef int difference_type;
1254
typedef const Value& reference;
1255
typedef const Value* pointer;
1256
typedef ValueConstIterator SelfType;
1257
1258
ValueConstIterator();
1259
ValueConstIterator(ValueIterator const& other);
1260
1261
private:
1262
/*! \internal Use by Value to create an iterator.
1263
*/
1264
explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
1265
public:
1266
SelfType& operator=(const ValueIteratorBase& other);
1267
1268
SelfType operator++(int) {
1269
SelfType temp(*this);
1270
++*this;
1271
return temp;
1272
}
1273
1274
SelfType operator--(int) {
1275
SelfType temp(*this);
1276
--*this;
1277
return temp;
1278
}
1279
1280
SelfType& operator--() {
1281
decrement();
1282
return *this;
1283
}
1284
1285
SelfType& operator++() {
1286
increment();
1287
return *this;
1288
}
1289
1290
reference operator*() const { return deref(); }
1291
1292
pointer operator->() const { return &deref(); }
1293
};
1294
1295
/** \brief Iterator for object and array value.
1296
*/
1297
class JSON_API ValueIterator : public ValueIteratorBase {
1298
friend class Value;
1299
1300
public:
1301
typedef Value value_type;
1302
typedef unsigned int size_t;
1303
typedef int difference_type;
1304
typedef Value& reference;
1305
typedef Value* pointer;
1306
typedef ValueIterator SelfType;
1307
1308
ValueIterator();
1309
explicit ValueIterator(const ValueConstIterator& other);
1310
ValueIterator(const ValueIterator& other);
1311
1312
private:
1313
/*! \internal Use by Value to create an iterator.
1314
*/
1315
explicit ValueIterator(const Value::ObjectValues::iterator& current);
1316
public:
1317
SelfType& operator=(const SelfType& other);
1318
1319
SelfType operator++(int) {
1320
SelfType temp(*this);
1321
++*this;
1322
return temp;
1323
}
1324
1325
SelfType operator--(int) {
1326
SelfType temp(*this);
1327
--*this;
1328
return temp;
1329
}
1330
1331
SelfType& operator--() {
1332
decrement();
1333
return *this;
1334
}
1335
1336
SelfType& operator++() {
1337
increment();
1338
return *this;
1339
}
1340
1341
reference operator*() const { return deref(); }
1342
1343
pointer operator->() const { return &deref(); }
1344
};
1345
1346
inline void swap(Value& a, Value& b) { a.swap(b); }
1347
1348
} // namespace Json
1349
1350
#pragma pack(pop)
1351
1352
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1353
#pragma warning(pop)
1354
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1355
1356
#endif // CPPTL_JSON_H_INCLUDED
1357
1358
// //////////////////////////////////////////////////////////////////////
1359
// End of content of file: include/json/value.h
1360
// //////////////////////////////////////////////////////////////////////
1361
1362
1363
1364
1365
1366
1367
// //////////////////////////////////////////////////////////////////////
1368
// Beginning of content of file: include/json/reader.h
1369
// //////////////////////////////////////////////////////////////////////
1370
1371
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
1372
// Distributed under MIT license, or public domain if desired and
1373
// recognized in your jurisdiction.
1374
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1375
1376
#ifndef CPPTL_JSON_READER_H_INCLUDED
1377
#define CPPTL_JSON_READER_H_INCLUDED
1378
1379
#if !defined(JSON_IS_AMALGAMATION)
1380
#include "features.h"
1381
#include "value.h"
1382
#endif // if !defined(JSON_IS_AMALGAMATION)
1383
#include <deque>
1384
#include <iosfwd>
1385
#include <stack>
1386
#include <string>
1387
#include <istream>
1388
1389
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
1390
// be used by...
1391
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1392
#pragma warning(push)
1393
#pragma warning(disable : 4251)
1394
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1395
1396
#pragma pack(push, 8)
1397
1398
namespace Json {
1399
1400
/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
1401
*Value.
1402
*
1403
* \deprecated Use CharReader and CharReaderBuilder.
1404
*/
1405
class JSON_API Reader {
1406
public:
1407
typedef char Char;
1408
typedef const Char* Location;
1409
1410
/** \brief An error tagged with where in the JSON text it was encountered.
1411
*
1412
* The offsets give the [start, limit) range of bytes within the text. Note
1413
* that this is bytes, not codepoints.
1414
*
1415
*/
1416
struct StructuredError {
1417
ptrdiff_t offset_start;
1418
ptrdiff_t offset_limit;
1419
JSONCPP_STRING message;
1420
};
1421
1422
/** \brief Constructs a Reader allowing all features
1423
* for parsing.
1424
*/
1425
JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead")
1426
Reader();
1427
1428
/** \brief Constructs a Reader allowing the specified feature set
1429
* for parsing.
1430
*/
1431
JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead")
1432
Reader(const Features& features);
1433
1434
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1435
* document.
1436
* \param document UTF-8 encoded string containing the document to read.
1437
* \param root [out] Contains the root value of the document if it was
1438
* successfully parsed.
1439
* \param collectComments \c true to collect comment and allow writing them
1440
* back during
1441
* serialization, \c false to discard comments.
1442
* This parameter is ignored if
1443
* Features::allowComments_
1444
* is \c false.
1445
* \return \c true if the document was successfully parsed, \c false if an
1446
* error occurred.
1447
*/
1448
bool
1449
parse(const std::string& document, Value& root, bool collectComments = true);
1450
1451
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1452
document.
1453
* \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1454
document to read.
1455
* \param endDoc Pointer on the end of the UTF-8 encoded string of the
1456
document to read.
1457
* Must be >= beginDoc.
1458
* \param root [out] Contains the root value of the document if it was
1459
* successfully parsed.
1460
* \param collectComments \c true to collect comment and allow writing them
1461
back during
1462
* serialization, \c false to discard comments.
1463
* This parameter is ignored if
1464
Features::allowComments_
1465
* is \c false.
1466
* \return \c true if the document was successfully parsed, \c false if an
1467
error occurred.
1468
*/
1469
bool parse(const char* beginDoc,
1470
const char* endDoc,
1471
Value& root,
1472
bool collectComments = true);
1473
1474
/// \brief Parse from input stream.
1475
/// \see Json::operator>>(std::istream&, Json::Value&).
1476
bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true);
1477
1478
/** \brief Returns a user friendly string that list errors in the parsed
1479
* document.
1480
* \return Formatted error message with the list of errors with their location
1481
* in
1482
* the parsed document. An empty string is returned if no error
1483
* occurred
1484
* during parsing.
1485
* \deprecated Use getFormattedErrorMessages() instead (typo fix).
1486
*/
1487
JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
1488
JSONCPP_STRING getFormatedErrorMessages() const;
1489
1490
/** \brief Returns a user friendly string that list errors in the parsed
1491
* document.
1492
* \return Formatted error message with the list of errors with their location
1493
* in
1494
* the parsed document. An empty string is returned if no error
1495
* occurred
1496
* during parsing.
1497
*/
1498
JSONCPP_STRING getFormattedErrorMessages() const;
1499
1500
/** \brief Returns a vector of structured erros encounted while parsing.
1501
* \return A (possibly empty) vector of StructuredError objects. Currently
1502
* only one error can be returned, but the caller should tolerate
1503
* multiple
1504
* errors. This can occur if the parser recovers from a non-fatal
1505
* parse error and then encounters additional errors.
1506
*/
1507
std::vector<StructuredError> getStructuredErrors() const;
1508
1509
/** \brief Add a semantic error message.
1510
* \param value JSON Value location associated with the error
1511
* \param message The error message.
1512
* \return \c true if the error was successfully added, \c false if the
1513
* Value offset exceeds the document size.
1514
*/
1515
bool pushError(const Value& value, const JSONCPP_STRING& message);
1516
1517
/** \brief Add a semantic error message with extra context.
1518
* \param value JSON Value location associated with the error
1519
* \param message The error message.
1520
* \param extra Additional JSON Value location to contextualize the error
1521
* \return \c true if the error was successfully added, \c false if either
1522
* Value offset exceeds the document size.
1523
*/
1524
bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
1525
1526
/** \brief Return whether there are any errors.
1527
* \return \c true if there are no errors to report \c false if
1528
* errors have occurred.
1529
*/
1530
bool good() const;
1531
1532
private:
1533
enum TokenType {
1534
tokenEndOfStream = 0,
1535
tokenObjectBegin,
1536
tokenObjectEnd,
1537
tokenArrayBegin,
1538
tokenArrayEnd,
1539
tokenString,
1540
tokenNumber,
1541
tokenTrue,
1542
tokenFalse,
1543
tokenNull,
1544
tokenArraySeparator,
1545
tokenMemberSeparator,
1546
tokenComment,
1547
tokenError
1548
};
1549
1550
class Token {
1551
public:
1552
TokenType type_;
1553
Location start_;
1554
Location end_;
1555
};
1556
1557
class ErrorInfo {
1558
public:
1559
Token token_;
1560
JSONCPP_STRING message_;
1561
Location extra_;
1562
};
1563
1564
typedef std::deque<ErrorInfo> Errors;
1565
1566
bool readToken(Token& token);
1567
void skipSpaces();
1568
bool match(Location pattern, int patternLength);
1569
bool readComment();
1570
bool readCStyleComment();
1571
bool readCppStyleComment();
1572
bool readString();
1573
void readNumber();
1574
bool readValue();
1575
bool readObject(Token& token);
1576
bool readArray(Token& token);
1577
bool decodeNumber(Token& token);
1578
bool decodeNumber(Token& token, Value& decoded);
1579
bool decodeString(Token& token);
1580
bool decodeString(Token& token, JSONCPP_STRING& decoded);
1581
bool decodeDouble(Token& token);
1582
bool decodeDouble(Token& token, Value& decoded);
1583
bool decodeUnicodeCodePoint(Token& token,
1584
Location& current,
1585
Location end,
1586
unsigned int& unicode);
1587
bool decodeUnicodeEscapeSequence(Token& token,
1588
Location& current,
1589
Location end,
1590
unsigned int& unicode);
1591
bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
1592
bool recoverFromError(TokenType skipUntilToken);
1593
bool addErrorAndRecover(const JSONCPP_STRING& message,
1594
Token& token,
1595
TokenType skipUntilToken);
1596
void skipUntilSpace();
1597
Value& currentValue();
1598
Char getNextChar();
1599
void
1600
getLocationLineAndColumn(Location location, int& line, int& column) const;
1601
JSONCPP_STRING getLocationLineAndColumn(Location location) const;
1602
void addComment(Location begin, Location end, CommentPlacement placement);
1603
void skipCommentTokens(Token& token);
1604
1605
static bool containsNewLine(Location begin, Location end);
1606
static JSONCPP_STRING normalizeEOL(Location begin, Location end);
1607
1608
typedef std::stack<Value*> Nodes;
1609
Nodes nodes_;
1610
Errors errors_;
1611
JSONCPP_STRING document_;
1612
Location begin_;
1613
Location end_;
1614
Location current_;
1615
Location lastValueEnd_;
1616
Value* lastValue_;
1617
JSONCPP_STRING commentsBefore_;
1618
Features features_;
1619
bool collectComments_;
1620
}; // Reader
1621
1622
/** Interface for reading JSON from a char array.
1623
*/
1624
class JSON_API CharReader {
1625
public:
1626
virtual ~CharReader() {}
1627
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
1628
document.
1629
* The document must be a UTF-8 encoded string containing the document to read.
1630
*
1631
* \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
1632
document to read.
1633
* \param endDoc Pointer on the end of the UTF-8 encoded string of the
1634
document to read.
1635
* Must be >= beginDoc.
1636
* \param root [out] Contains the root value of the document if it was
1637
* successfully parsed.
1638
* \param errs [out] Formatted error messages (if not NULL)
1639
* a user friendly string that lists errors in the parsed
1640
* document.
1641
* \return \c true if the document was successfully parsed, \c false if an
1642
error occurred.
1643
*/
1644
virtual bool parse(
1645
char const* beginDoc, char const* endDoc,
1646
Value* root, JSONCPP_STRING* errs) = 0;
1647
1648
class JSON_API Factory {
1649
public:
1650
virtual ~Factory() {}
1651
/** \brief Allocate a CharReader via operator new().
1652
* \throw std::exception if something goes wrong (e.g. invalid settings)
1653
*/
1654
virtual CharReader* newCharReader() const = 0;
1655
}; // Factory
1656
}; // CharReader
1657
1658
/** \brief Build a CharReader implementation.
1659
1660
Usage:
1661
\code
1662
using namespace Json;
1663
CharReaderBuilder builder;
1664
builder["collectComments"] = false;
1665
Value value;
1666
JSONCPP_STRING errs;
1667
bool ok = parseFromStream(builder, std::cin, &value, &errs);
1668
\endcode
1669
*/
1670
class JSON_API CharReaderBuilder : public CharReader::Factory {
1671
public:
1672
// Note: We use a Json::Value so that we can add data-members to this class
1673
// without a major version bump.
1674
/** Configuration of this builder.
1675
These are case-sensitive.
1676
Available settings (case-sensitive):
1677
- `"collectComments": false or true`
1678
- true to collect comment and allow writing them
1679
back during serialization, false to discard comments.
1680
This parameter is ignored if allowComments is false.
1681
- `"allowComments": false or true`
1682
- true if comments are allowed.
1683
- `"strictRoot": false or true`
1684
- true if root must be either an array or an object value
1685
- `"allowDroppedNullPlaceholders": false or true`
1686
- true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
1687
- `"allowNumericKeys": false or true`
1688
- true if numeric object keys are allowed.
1689
- `"allowSingleQuotes": false or true`
1690
- true if '' are allowed for strings (both keys and values)
1691
- `"stackLimit": integer`
1692
- Exceeding stackLimit (recursive depth of `readValue()`) will
1693
cause an exception.
1694
- This is a security issue (seg-faults caused by deeply nested JSON),
1695
so the default is low.
1696
- `"failIfExtra": false or true`
1697
- If true, `parse()` returns false when extra non-whitespace trails
1698
the JSON value in the input string.
1699
- `"rejectDupKeys": false or true`
1700
- If true, `parse()` returns false when a key is duplicated within an object.
1701
- `"allowSpecialFloats": false or true`
1702
- If true, special float values (NaNs and infinities) are allowed
1703
and their values are lossfree restorable.
1704
1705
You can examine 'settings_` yourself
1706
to see the defaults. You can also write and read them just like any
1707
JSON Value.
1708
\sa setDefaults()
1709
*/
1710
Json::Value settings_;
1711
1712
CharReaderBuilder();
1713
~CharReaderBuilder() JSONCPP_OVERRIDE;
1714
1715
CharReader* newCharReader() const JSONCPP_OVERRIDE;
1716
1717
/** \return true if 'settings' are legal and consistent;
1718
* otherwise, indicate bad settings via 'invalid'.
1719
*/
1720
bool validate(Json::Value* invalid) const;
1721
1722
/** A simple way to update a specific setting.
1723
*/
1724
Value& operator[](JSONCPP_STRING key);
1725
1726
/** Called by ctor, but you can use this to reset settings_.
1727
* \pre 'settings' != NULL (but Json::null is fine)
1728
* \remark Defaults:
1729
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
1730
*/
1731
static void setDefaults(Json::Value* settings);
1732
/** Same as old Features::strictMode().
1733
* \pre 'settings' != NULL (but Json::null is fine)
1734
* \remark Defaults:
1735
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
1736
*/
1737
static void strictMode(Json::Value* settings);
1738
};
1739
1740
/** Consume entire stream and use its begin/end.
1741
* Someday we might have a real StreamReader, but for now this
1742
* is convenient.
1743
*/
1744
bool JSON_API parseFromStream(
1745
CharReader::Factory const&,
1746
JSONCPP_ISTREAM&,
1747
Value* root, std::string* errs);
1748
1749
/** \brief Read from 'sin' into 'root'.
1750
1751
Always keep comments from the input JSON.
1752
1753
This can be used to read a file into a particular sub-object.
1754
For example:
1755
\code
1756
Json::Value root;
1757
cin >> root["dir"]["file"];
1758
cout << root;
1759
\endcode
1760
Result:
1761
\verbatim
1762
{
1763
"dir": {
1764
"file": {
1765
// The input stream JSON would be nested here.
1766
}
1767
}
1768
}
1769
\endverbatim
1770
\throw std::exception on parse error.
1771
\see Json::operator<<()
1772
*/
1773
JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
1774
1775
} // namespace Json
1776
1777
#pragma pack(pop)
1778
1779
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1780
#pragma warning(pop)
1781
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1782
1783
#endif // CPPTL_JSON_READER_H_INCLUDED
1784
1785
// //////////////////////////////////////////////////////////////////////
1786
// End of content of file: include/json/reader.h
1787
// //////////////////////////////////////////////////////////////////////
1788
1789
1790
1791
1792
1793
1794
// //////////////////////////////////////////////////////////////////////
1795
// Beginning of content of file: include/json/writer.h
1796
// //////////////////////////////////////////////////////////////////////
1797
1798
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
1799
// Distributed under MIT license, or public domain if desired and
1800
// recognized in your jurisdiction.
1801
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
1802
1803
#ifndef JSON_WRITER_H_INCLUDED
1804
#define JSON_WRITER_H_INCLUDED
1805
1806
#if !defined(JSON_IS_AMALGAMATION)
1807
#include "value.h"
1808
#endif // if !defined(JSON_IS_AMALGAMATION)
1809
#include <vector>
1810
#include <string>
1811
#include <ostream>
1812
1813
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
1814
// be used by...
1815
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER)
1816
#pragma warning(push)
1817
#pragma warning(disable : 4251)
1818
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
1819
1820
#pragma pack(push, 8)
1821
1822
namespace Json {
1823
1824
class Value;
1825
1826
/**
1827
1828
Usage:
1829
\code
1830
using namespace Json;
1831
void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
1832
std::unique_ptr<StreamWriter> const writer(
1833
factory.newStreamWriter());
1834
writer->write(value, &std::cout);
1835
std::cout << std::endl; // add lf and flush
1836
}
1837
\endcode
1838
*/
1839
class JSON_API StreamWriter {
1840
protected:
1841
JSONCPP_OSTREAM* sout_; // not owned; will not delete
1842
public:
1843
StreamWriter();
1844
virtual ~StreamWriter();
1845
/** Write Value into document as configured in sub-class.
1846
Do not take ownership of sout, but maintain a reference during function.
1847
\pre sout != NULL
1848
\return zero on success (For now, we always return zero, so check the stream instead.)
1849
\throw std::exception possibly, depending on configuration
1850
*/
1851
virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0;
1852
1853
/** \brief A simple abstract factory.
1854
*/
1855
class JSON_API Factory {
1856
public:
1857
virtual ~Factory();
1858
/** \brief Allocate a CharReader via operator new().
1859
* \throw std::exception if something goes wrong (e.g. invalid settings)
1860
*/
1861
virtual StreamWriter* newStreamWriter() const = 0;
1862
}; // Factory
1863
}; // StreamWriter
1864
1865
/** \brief Write into stringstream, then return string, for convenience.
1866
* A StreamWriter will be created from the factory, used, and then deleted.
1867
*/
1868
JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
1869
1870
1871
/** \brief Build a StreamWriter implementation.
1872
1873
Usage:
1874
\code
1875
using namespace Json;
1876
Value value = ...;
1877
StreamWriterBuilder builder;
1878
builder["commentStyle"] = "None";
1879
builder["indentation"] = " "; // or whatever you like
1880
std::unique_ptr<Json::StreamWriter> writer(
1881
builder.newStreamWriter());
1882
writer->write(value, &std::cout);
1883
std::cout << std::endl; // add lf and flush
1884
\endcode
1885
*/
1886
class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
1887
public:
1888
// Note: We use a Json::Value so that we can add data-members to this class
1889
// without a major version bump.
1890
/** Configuration of this builder.
1891
Available settings (case-sensitive):
1892
- "commentStyle": "None" or "All"
1893
- "indentation": "<anything>".
1894
- Setting this to an empty string also omits newline characters.
1895
- "enableYAMLCompatibility": false or true
1896
- slightly change the whitespace around colons
1897
- "dropNullPlaceholders": false or true
1898
- Drop the "null" string from the writer's output for nullValues.
1899
Strictly speaking, this is not valid JSON. But when the output is being
1900
fed to a browser's JavaScript, it makes for smaller output and the
1901
browser can handle the output just fine.
1902
- "useSpecialFloats": false or true
1903
- If true, outputs non-finite floating point values in the following way:
1904
NaN values as "NaN", positive infinity as "Infinity", and negative infinity
1905
as "-Infinity".
1906
- "precision": int
1907
- Number of precision digits for formatting of real values.
1908
- "precisionType": "significant"(default) or "decimal"
1909
- Type of precision for formatting of real values.
1910
1911
You can examine 'settings_` yourself
1912
to see the defaults. You can also write and read them just like any
1913
JSON Value.
1914
\sa setDefaults()
1915
*/
1916
Json::Value settings_;
1917
1918
StreamWriterBuilder();
1919
~StreamWriterBuilder() JSONCPP_OVERRIDE;
1920
1921
/**
1922
* \throw std::exception if something goes wrong (e.g. invalid settings)
1923
*/
1924
StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE;
1925
1926
/** \return true if 'settings' are legal and consistent;
1927
* otherwise, indicate bad settings via 'invalid'.
1928
*/
1929
bool validate(Json::Value* invalid) const;
1930
/** A simple way to update a specific setting.
1931
*/
1932
Value& operator[](JSONCPP_STRING key);
1933
1934
/** Called by ctor, but you can use this to reset settings_.
1935
* \pre 'settings' != NULL (but Json::null is fine)
1936
* \remark Defaults:
1937
* \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
1938
*/
1939
static void setDefaults(Json::Value* settings);
1940
};
1941
1942
/** \brief Abstract class for writers.
1943
* \deprecated Use StreamWriter. (And really, this is an implementation detail.)
1944
*/
1945
class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer {
1946
public:
1947
virtual ~Writer();
1948
1949
virtual JSONCPP_STRING write(const Value& root) = 0;
1950
};
1951
1952
/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
1953
*without formatting (not human friendly).
1954
*
1955
* The JSON document is written in a single line. It is not intended for 'human'
1956
*consumption,
1957
* but may be useful to support feature such as RPC where bandwidth is limited.
1958
* \sa Reader, Value
1959
* \deprecated Use StreamWriterBuilder.
1960
*/
1961
#if defined(_MSC_VER)
1962
#pragma warning(push)
1963
#pragma warning(disable:4996) // Deriving from deprecated class
1964
#endif
1965
class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter : public Writer {
1966
public:
1967
FastWriter();
1968
~FastWriter() JSONCPP_OVERRIDE {}
1969
1970
void enableYAMLCompatibility();
1971
1972
/** \brief Drop the "null" string from the writer's output for nullValues.
1973
* Strictly speaking, this is not valid JSON. But when the output is being
1974
* fed to a browser's JavaScript, it makes for smaller output and the
1975
* browser can handle the output just fine.
1976
*/
1977
void dropNullPlaceholders();
1978
1979
void omitEndingLineFeed();
1980
1981
public: // overridden from Writer
1982
JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
1983
1984
private:
1985
void writeValue(const Value& value);
1986
1987
JSONCPP_STRING document_;
1988
bool yamlCompatibilityEnabled_;
1989
bool dropNullPlaceholders_;
1990
bool omitEndingLineFeed_;
1991
};
1992
#if defined(_MSC_VER)
1993
#pragma warning(pop)
1994
#endif
1995
1996
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
1997
*human friendly way.
1998
*
1999
* The rules for line break and indent are as follow:
2000
* - Object value:
2001
* - if empty then print {} without indent and line break
2002
* - if not empty the print '{', line break & indent, print one value per
2003
*line
2004
* and then unindent and line break and print '}'.
2005
* - Array value:
2006
* - if empty then print [] without indent and line break
2007
* - if the array contains no object value, empty array or some other value
2008
*types,
2009
* and all the values fit on one lines, then print the array on a single
2010
*line.
2011
* - otherwise, it the values do not fit on one line, or the array contains
2012
* object or non empty array, then print one value per line.
2013
*
2014
* If the Value have comments then they are outputed according to their
2015
*#CommentPlacement.
2016
*
2017
* \sa Reader, Value, Value::setComment()
2018
* \deprecated Use StreamWriterBuilder.
2019
*/
2020
#if defined(_MSC_VER)
2021
#pragma warning(push)
2022
#pragma warning(disable:4996) // Deriving from deprecated class
2023
#endif
2024
class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter : public Writer {
2025
public:
2026
StyledWriter();
2027
~StyledWriter() JSONCPP_OVERRIDE {}
2028
2029
public: // overridden from Writer
2030
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
2031
* \param root Value to serialize.
2032
* \return String containing the JSON document that represents the root value.
2033
*/
2034
JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
2035
2036
private:
2037
void writeValue(const Value& value);
2038
void writeArrayValue(const Value& value);
2039
bool isMultilineArray(const Value& value);
2040
void pushValue(const JSONCPP_STRING& value);
2041
void writeIndent();
2042
void writeWithIndent(const JSONCPP_STRING& value);
2043
void indent();
2044
void unindent();
2045
void writeCommentBeforeValue(const Value& root);
2046
void writeCommentAfterValueOnSameLine(const Value& root);
2047
bool hasCommentForValue(const Value& value);
2048
static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
2049
2050
typedef std::vector<JSONCPP_STRING> ChildValues;
2051
2052
ChildValues childValues_;
2053
JSONCPP_STRING document_;
2054
JSONCPP_STRING indentString_;
2055
unsigned int rightMargin_;
2056
unsigned int indentSize_;
2057
bool addChildValues_;
2058
};
2059
#if defined(_MSC_VER)
2060
#pragma warning(pop)
2061
#endif
2062
2063
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
2064
human friendly way,
2065
to a stream rather than to a string.
2066
*
2067
* The rules for line break and indent are as follow:
2068
* - Object value:
2069
* - if empty then print {} without indent and line break
2070
* - if not empty the print '{', line break & indent, print one value per
2071
line
2072
* and then unindent and line break and print '}'.
2073
* - Array value:
2074
* - if empty then print [] without indent and line break
2075
* - if the array contains no object value, empty array or some other value
2076
types,
2077
* and all the values fit on one lines, then print the array on a single
2078
line.
2079
* - otherwise, it the values do not fit on one line, or the array contains
2080
* object or non empty array, then print one value per line.
2081
*
2082
* If the Value have comments then they are outputed according to their
2083
#CommentPlacement.
2084
*
2085
* \sa Reader, Value, Value::setComment()
2086
* \deprecated Use StreamWriterBuilder.
2087
*/
2088
#if defined(_MSC_VER)
2089
#pragma warning(push)
2090
#pragma warning(disable:4996) // Deriving from deprecated class
2091
#endif
2092
class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter {
2093
public:
2094
/**
2095
* \param indentation Each level will be indented by this amount extra.
2096
*/
2097
StyledStreamWriter(JSONCPP_STRING indentation = "\t");
2098
~StyledStreamWriter() {}
2099
2100
public:
2101
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
2102
* \param out Stream to write to. (Can be ostringstream, e.g.)
2103
* \param root Value to serialize.
2104
* \note There is no point in deriving from Writer, since write() should not
2105
* return a value.
2106
*/
2107
void write(JSONCPP_OSTREAM& out, const Value& root);
2108
2109
private:
2110
void writeValue(const Value& value);
2111
void writeArrayValue(const Value& value);
2112
bool isMultilineArray(const Value& value);
2113
void pushValue(const JSONCPP_STRING& value);
2114
void writeIndent();
2115
void writeWithIndent(const JSONCPP_STRING& value);
2116
void indent();
2117
void unindent();
2118
void writeCommentBeforeValue(const Value& root);
2119
void writeCommentAfterValueOnSameLine(const Value& root);
2120
bool hasCommentForValue(const Value& value);
2121
static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
2122
2123
typedef std::vector<JSONCPP_STRING> ChildValues;
2124
2125
ChildValues childValues_;
2126
JSONCPP_OSTREAM* document_;
2127
JSONCPP_STRING indentString_;
2128
unsigned int rightMargin_;
2129
JSONCPP_STRING indentation_;
2130
bool addChildValues_ : 1;
2131
bool indented_ : 1;
2132
};
2133
#if defined(_MSC_VER)
2134
#pragma warning(pop)
2135
#endif
2136
2137
#if defined(JSON_HAS_INT64)
2138
JSONCPP_STRING JSON_API valueToString(Int value);
2139
JSONCPP_STRING JSON_API valueToString(UInt value);
2140
#endif // if defined(JSON_HAS_INT64)
2141
JSONCPP_STRING JSON_API valueToString(LargestInt value);
2142
JSONCPP_STRING JSON_API valueToString(LargestUInt value);
2143
JSONCPP_STRING JSON_API valueToString(double value, unsigned int precision = Value::defaultRealPrecision,
2144
PrecisionType precisionType = PrecisionType::significantDigits);
2145
JSONCPP_STRING JSON_API valueToString(bool value);
2146
JSONCPP_STRING JSON_API valueToQuotedString(const char* value);
2147
2148
/// \brief Output using the StyledStreamWriter.
2149
/// \see Json::operator>>()
2150
JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
2151
2152
} // namespace Json
2153
2154
#pragma pack(pop)
2155
2156
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2157
#pragma warning(pop)
2158
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
2159
2160
#endif // JSON_WRITER_H_INCLUDED
2161
2162
// //////////////////////////////////////////////////////////////////////
2163
// End of content of file: include/json/writer.h
2164
// //////////////////////////////////////////////////////////////////////
2165
2166
2167
2168
2169
2170
2171
// //////////////////////////////////////////////////////////////////////
2172
// Beginning of content of file: include/json/assertions.h
2173
// //////////////////////////////////////////////////////////////////////
2174
2175
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2176
// Distributed under MIT license, or public domain if desired and
2177
// recognized in your jurisdiction.
2178
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2179
2180
#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
2181
#define CPPTL_JSON_ASSERTIONS_H_INCLUDED
2182
2183
#include <stdlib.h>
2184
#include <sstream>
2185
2186
#if !defined(JSON_IS_AMALGAMATION)
2187
#include "config.h"
2188
#endif // if !defined(JSON_IS_AMALGAMATION)
2189
2190
/** It should not be possible for a maliciously designed file to
2191
* cause an abort() or seg-fault, so these macros are used only
2192
* for pre-condition violations and internal logic errors.
2193
*/
2194
#if JSON_USE_EXCEPTION
2195
2196
// @todo <= add detail about condition in exception
2197
# define JSON_ASSERT(condition) \
2198
{if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
2199
2200
# define JSON_FAIL_MESSAGE(message) \
2201
{ \
2202
JSONCPP_OSTRINGSTREAM oss; oss << message; \
2203
Json::throwLogicError(oss.str()); \
2204
abort(); \
2205
}
2206
2207
#else // JSON_USE_EXCEPTION
2208
2209
# define JSON_ASSERT(condition) assert(condition)
2210
2211
// The call to assert() will show the failure message in debug builds. In
2212
// release builds we abort, for a core-dump or debugger.
2213
# define JSON_FAIL_MESSAGE(message) \
2214
{ \
2215
JSONCPP_OSTRINGSTREAM oss; oss << message; \
2216
assert(false && oss.str().c_str()); \
2217
abort(); \
2218
}
2219
2220
2221
#endif
2222
2223
#define JSON_ASSERT_MESSAGE(condition, message) \
2224
if (!(condition)) { \
2225
JSON_FAIL_MESSAGE(message); \
2226
}
2227
2228
#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
2229
2230
// //////////////////////////////////////////////////////////////////////
2231
// End of content of file: include/json/assertions.h
2232
// //////////////////////////////////////////////////////////////////////
2233
2234
2235
2236
2237
2238
#endif //ifndef JSON_AMALGAMATED_H_INCLUDED
2239
2240