forked from pocoproject/poco
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObject.h
More file actions
789 lines (626 loc) · 16.5 KB
/
Object.h
File metadata and controls
789 lines (626 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//
// Object.h
//
// Library: JSON
// Package: JSON
// Module: Object
//
// Definition of the Object class.
//
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef JSON_Object_INCLUDED
#define JSON_Object_INCLUDED
#include "Poco/JSON/JSON.h"
#include "Poco/JSON/Array.h"
#include "Poco/JSON/Stringifier.h"
#include "Poco/JSONString.h"
#include "Poco/SharedPtr.h"
#include "Poco/Dynamic/Var.h"
#include "Poco/Dynamic/Struct.h"
#include "Poco/Nullable.h"
#include <map>
#include <vector>
#include <deque>
#include <iostream>
#include <sstream>
namespace Poco {
namespace JSON {
class JSON_API Object
/// Represents a JSON object. Object provides a representation based on
/// shared pointers and optimized for performance. It is possible to
/// convert Object to DynamicStruct. Conversion requires copying and therefore
/// has performance penalty; the benefit is in improved syntax, eg:
///
/// std::string json = "{ \"test\" : { \"property\" : \"value\" } }";
/// Parser parser;
/// Var result = parser.parse(json);
///
/// // use pointers to avoid copying
/// Object::Ptr object = result.extract<Object::Ptr>();
/// Var test = object->get("test"); // holds { "property" : "value" }
/// Object::Ptr subObject = test.extract<Object::Ptr>();
/// test = subObject->get("property");
/// std::string val = test.toString(); // val holds "value"
///
/// // copy/convert to Poco::DynamicStruct
/// Poco::DynamicStruct ds = *object;
/// val = ds["test"]["property"]; // val holds "value"
///
{
public:
using Ptr = SharedPtr<Object>;
using ValueMap = std::map<std::string, Dynamic::Var>;
using ValueType = ValueMap::value_type;
using Iterator = ValueMap::iterator;
using ConstIterator = ValueMap::const_iterator;
using NameList = std::vector<std::string>;
explicit Object(int options = 0);
/// Creates an empty Object.
///
/// If JSON_PRESERVE_KEY_ORDER is specified, the object will
/// preserve the items insertion order. Otherwise, items will be
/// sorted by keys.
///
/// If JSON_ESCAPE_UNICODE is specified, when the object is
/// stringified, all unicode characters will be escaped in the
/// resulting string.
Object(const Object& copy);
/// Creates an Object by copying another one.
///
/// Struct is not copied to keep the operation as
/// efficient as possible (when needed, it will be generated upon request).
Object(Object&& other) noexcept;
/// Move constructor
~Object();
/// Destroys the Object.
Object &operator = (const Object &other);
// Assignment operator
Object &operator = (Object &&other) noexcept;
// Move asignment operator
void setEscapeUnicode(bool escape = true);
/// Sets the flag for escaping unicode.
bool getEscapeUnicode() const;
/// Returns the flag for escaping unicode.
Iterator begin();
/// Returns begin iterator for values.
ConstIterator begin() const;
/// Returns const begin iterator for values.
Iterator end();
/// Returns end iterator for values.
ConstIterator end() const;
/// Returns const end iterator for values.
Dynamic::Var get(const std::string& key) const;
/// Retrieves a property. An empty value is
/// returned when the property doesn't exist.
Array::Ptr getArray(const std::string& key) const;
/// Returns a SharedPtr to an array when the property
/// is an array. An empty SharedPtr is returned when
/// the element doesn't exist or is not an array.
Object::Ptr getObject(const std::string& key) const;
/// Returns a SharedPtr to an object when the property
/// is an object. An empty SharedPtr is returned when
/// the property doesn't exist or is not an object
template<typename T>
T getValue(const std::string& key) const
/// Retrieves the property with the given name and will
/// try to convert the value to the given template type.
/// The convert<T>() method of Var is called
/// which can also throw exceptions for invalid values.
/// Note: This will not work for an array or an object.
{
Dynamic::Var value = get(key);
return value.convert<T>();
}
template<typename T>
void copyValue(T& t, const std::string& key)
/// copyValue is like getValue
/// The difference is that it can be directly assigned to t
/// Note: This will not work for an array or an object.
{
t = this->get(key).convert<T>();
}
template<typename T>
Poco::Nullable<T> getNullableValue(const std::string& key) const
/// Retrieves the property with the given name and will
/// try to convert the value to the given template type.
///
/// The convert<T> method of Var is called
/// which can also throw exceptions for invalid values.
/// Note: This will not work for an array or an object.
{
if (isNull(key))
return Poco::Nullable<T>();
Dynamic::Var value = get(key);
return value.convert<T>();
}
void getNames(NameList& names) const;
/// Fills the supplied vector with all property names.
NameList getNames() const;
/// Returns all property names.
bool has(const std::string& key) const;
/// Returns true when the given property exists.
bool isArray(const std::string& key) const;
/// Returns true when the given property contains an array.
bool isArray(ConstIterator& it) const;
/// Returns true when the given property contains an array.
bool isNull(const std::string& key) const;
/// Returns true when the given property contains a null value.
bool isObject(const std::string& key) const;
/// Returns true when the given property contains an object.
bool isObject(ConstIterator& it) const;
/// Returns true when the given property contains an object.
template<typename T>
T optValue(const std::string& key, const T& def) const
/// Returns the value of a property when the property exists
/// and can be converted to the given type. Otherwise
/// def will be returned.
{
T value = def;
ValueMap::const_iterator it = _values.find(key);
if (it != _values.end() && ! it->second.isEmpty())
{
try
{
value = it->second.convert<T>();
}
catch (...)
{
// The default value will be returned
}
}
return value;
}
std::size_t size() const;
/// Returns the number of properties.
Object& set(const std::string& key, const Dynamic::Var& value);
/// Sets a new value.
void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const;
/// Prints the object to out stream.
///
/// When indent is 0, the object will be printed on a single
/// line without indentation.
void remove(const std::string& key);
/// Removes the property with the given key.
static Poco::DynamicStruct makeStruct(const Object::Ptr& obj);
/// Utility function for creation of struct.
static Poco::OrderedDynamicStruct makeOrderedStruct(const Object::Ptr& obj);
/// Utility function for creation of ordered struct.
operator const Poco::OrderedDynamicStruct& () const;
/// Cast operator to Poco::OrderedDynamiStruct.
operator const Poco::DynamicStruct& () const;
/// Cast operator to Poco::DynamiStruct.
void clear();
/// Clears the contents of the object.
///
/// Insertion order preservation property is left intact.
private:
typedef std::deque<ValueMap::const_iterator> KeyList;
typedef Poco::DynamicStruct::Ptr StructPtr;
typedef Poco::OrderedDynamicStruct::Ptr OrdStructPtr;
void syncKeys(const KeyList& keys);
template <typename T>
void resetDynStruct(T& pStruct) const
{
if (!pStruct)
pStruct = new typename T::Type;
else
pStruct->clear();
}
template <typename C>
void doStringify(const C& container, std::ostream& out, unsigned int indent, unsigned int step) const
{
int options = Poco::JSON_WRAP_STRINGS;
options |= _escapeUnicode ? Poco::JSON_ESCAPE_UNICODE : 0;
out << '{';
if (indent > 0) out << std::endl;
typename C::const_iterator it = container.begin();
typename C::const_iterator end = container.end();
for (; it != end;)
{
for (unsigned int i = 0; i < indent; i++) out << ' ';
Stringifier::stringify(getKey(it), out, indent, step, options);
out << ((indent > 0) ? " : " : ":");
Stringifier::stringify(getValue(it), out, indent + step, step, options);
if (++it != container.end()) out << ',';
if (step > 0) out << std::endl;
}
if (indent >= step) indent -= step;
for (unsigned int i = 0; i < indent; i++) out << ' ';
out << '}';
}
template <typename S>
static S makeStructImpl(const Object::Ptr& obj)
{
S ds;
if (obj->_preserveInsOrder)
{
KeyList::const_iterator it = obj->_keys.begin();
KeyList::const_iterator end = obj->_keys.end();
for (; it != end; ++it)
{
if (obj->isObject((*it)->first))
{
Object::Ptr pObj = obj->getObject((*it)->first);
S str = makeStructImpl<S>(pObj);
ds.insert((*it)->first, str);
}
else if (obj->isArray((*it)->first))
{
Array::Ptr pArr = obj->getArray((*it)->first);
std::vector<Poco::Dynamic::Var> v = Poco::JSON::Array::makeArray(pArr);
ds.insert((*it)->first, v);
}
else
ds.insert((*it)->first, (*it)->second);
}
}
else
{
ConstIterator it = obj->begin();
ConstIterator end = obj->end();
for (; it != end; ++it)
{
if (obj->isObject(it))
{
Object::Ptr pObj = obj->getObject(it->first);
S str = makeStructImpl<S>(pObj);
ds.insert(it->first, str);
}
else if (obj->isArray(it))
{
Array::Ptr pArr = obj->getArray(it->first);
std::vector<Poco::Dynamic::Var> v = Poco::JSON::Array::makeArray(pArr);
ds.insert(it->first, v);
}
else
ds.insert(it->first, it->second);
}
}
return ds;
}
const std::string& getKey(ValueMap::const_iterator& it) const;
const Dynamic::Var& getValue(ValueMap::const_iterator& it) const;
const std::string& getKey(KeyList::const_iterator& it) const;
const Dynamic::Var& getValue(KeyList::const_iterator& it) const;
ValueMap _values;
KeyList _keys;
bool _preserveInsOrder;
// Note:
// The reason for this flag (rather than as argument to stringify()) is
// because Object can be returned stringified from Dynamic::Var::toString(),
// so it must know whether to escape unicode or not.
bool _escapeUnicode;
mutable StructPtr _pStruct;
mutable OrdStructPtr _pOrdStruct;
mutable bool _modified;
};
//
// inlines
//
inline void Object::setEscapeUnicode(bool escape)
{
_escapeUnicode = escape;
}
inline bool Object::getEscapeUnicode() const
{
return _escapeUnicode;
}
inline Object::Iterator Object::begin()
{
return _values.begin();
}
inline Object::ConstIterator Object::begin() const
{
return _values.begin();
}
inline Object::Iterator Object::end()
{
return _values.end();
}
inline Object::ConstIterator Object::end() const
{
return _values.end();
}
inline bool Object::has(const std::string& key) const
{
ValueMap::const_iterator it = _values.find(key);
return it != _values.end();
}
inline bool Object::isArray(const std::string& key) const
{
ValueMap::const_iterator it = _values.find(key);
return isArray(it);
}
inline bool Object::isArray(ConstIterator& it) const
{
return it != _values.end() && (it->second.type() == typeid(Array::Ptr) || it->second.type() == typeid(Array));
}
inline bool Object::isNull(const std::string& key) const
{
ValueMap::const_iterator it = _values.find(key);
return it == _values.end() || it->second.isEmpty();
}
inline bool Object::isObject(const std::string& key) const
{
ValueMap::const_iterator it = _values.find(key);
return isObject(it);
}
inline bool Object::isObject(ConstIterator& it) const
{
return it != _values.end() && (it->second.type() == typeid(Object::Ptr) || it->second.type() == typeid(Object));
}
inline std::size_t Object::size() const
{
return static_cast<std::size_t>(_values.size());
}
inline void Object::remove(const std::string& key)
{
_values.erase(key);
if (_preserveInsOrder)
{
KeyList::iterator it = _keys.begin();
KeyList::iterator end = _keys.end();
for (; it != end; ++it)
{
if (key == (*it)->first)
{
_keys.erase(it);
break;
}
}
}
_modified = true;
}
inline const std::string& Object::getKey(ValueMap::const_iterator& it) const
{
return it->first;
}
inline const Dynamic::Var& Object::getValue(ValueMap::const_iterator& it) const
{
return it->second;
}
inline const Dynamic::Var& Object::getValue(KeyList::const_iterator& it) const
{
ValueMap::const_iterator itv = _values.find((*it)->first);
if (itv != _values.end())
return itv->second;
else
throw Poco::NotFoundException();
}
} } // namespace Poco::JSON
namespace Poco {
namespace Dynamic {
template <>
class VarHolderImpl<JSON::Object::Ptr>: public VarHolder
{
public:
VarHolderImpl(const JSON::Object::Ptr& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(JSON::Object::Ptr);
}
void convert(Int8&) const
{
throw BadCastException();
}
void convert(Int16&) const
{
throw BadCastException();
}
void convert(Int32&) const
{
throw BadCastException();
}
void convert(Int64&) const
{
throw BadCastException();
}
void convert(UInt8&) const
{
throw BadCastException();
}
void convert(UInt16&) const
{
throw BadCastException();
}
void convert(UInt32&) const
{
throw BadCastException();
}
void convert(UInt64&) const
{
throw BadCastException();
}
void convert(bool& value) const
{
value = !_val.isNull() && _val->size() > 0;
}
void convert(float&) const
{
throw BadCastException();
}
void convert(double&) const
{
throw BadCastException();
}
void convert(char&) const
{
throw BadCastException();
}
void convert(std::string& s) const
{
std::ostringstream oss;
_val->stringify(oss, 2);
s = oss.str();
}
void convert(DateTime& /*val*/) const
{
//TODO: val = _val;
throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime");
}
void convert(LocalDateTime& /*ldt*/) const
{
//TODO: ldt = _val.timestamp();
throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime");
}
void convert(Timestamp& /*ts*/) const
{
//TODO: ts = _val.timestamp();
throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp");
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const JSON::Object::Ptr& value() const
{
return _val;
}
bool isArray() const
{
return false;
}
bool isInteger() const
{
return false;
}
bool isSigned() const
{
return false;
}
bool isNumeric() const
{
return false;
}
bool isString() const
{
return false;
}
private:
JSON::Object::Ptr _val;
};
template <>
class VarHolderImpl<JSON::Object>: public VarHolder
{
public:
VarHolderImpl(const JSON::Object& val): _val(val)
{
}
~VarHolderImpl()
{
}
const std::type_info& type() const
{
return typeid(JSON::Object);
}
void convert(Int8&) const
{
throw BadCastException();
}
void convert(Int16&) const
{
throw BadCastException();
}
void convert(Int32&) const
{
throw BadCastException();
}
void convert(Int64&) const
{
throw BadCastException();
}
void convert(UInt8&) const
{
throw BadCastException();
}
void convert(UInt16&) const
{
throw BadCastException();
}
void convert(UInt32&) const
{
throw BadCastException();
}
void convert(UInt64&) const
{
throw BadCastException();
}
void convert(bool& value) const
{
value = _val.size() > 0;
}
void convert(float&) const
{
throw BadCastException();
}
void convert(double&) const
{
throw BadCastException();
}
void convert(char&) const
{
throw BadCastException();
}
void convert(std::string& s) const
{
std::ostringstream oss;
_val.stringify(oss, 2);
s = oss.str();
}
void convert(DateTime& /*val*/) const
{
//TODO: val = _val;
throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime");
}
void convert(LocalDateTime& /*ldt*/) const
{
//TODO: ldt = _val.timestamp();
throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime");
}
void convert(Timestamp& /*ts*/) const
{
//TODO: ts = _val.timestamp();
throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp");
}
VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const
{
return cloneHolder(pVarHolder, _val);
}
const JSON::Object& value() const
{
return _val;
}
bool isArray() const
{
return false;
}
bool isInteger() const
{
return false;
}
bool isSigned() const
{
return false;
}
bool isNumeric() const
{
return false;
}
bool isString() const
{
return false;
}
private:
JSON::Object _val;
};
} } // namespace Poco::Dynamic
#endif // JSON_Object_INCLUDED