-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON.hpp
More file actions
1657 lines (1387 loc) · 58.1 KB
/
JSON.hpp
File metadata and controls
1657 lines (1387 loc) · 58.1 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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MIT License
*
* Copyright (c) 2020 Christian Tost
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef JSON_HPP
#define JSON_HPP
#include <string>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <stdexcept>
#include <memory>
#include <string.h>
#include <vector>
/**
* @brief JSON exception type for faster exception processing.
*/
enum class JSONErrorType
{
NAME_ALREADY_EXITS, //!< Occurred if a key already exists.
NAME_NOT_FOUND, //!< Occurred if a key is not found.
INVALID_JSON_OBJECT,//!< Occurred if a json object is not valid.
INVALID_ARRAY, //!< Occurred if a json array is not valid.
INVALID_TYPE, //!< Occurred if an unknown type is found. Formally if '"' missing around string.
INVALID_CAST, //!< Occurred if a type couldn't cast to the given one.
EXPECTED_BOOL, //!< Occurred if a bool is expected but not found.
EXPECTED_NULL, //!< Occurred if a null type is expected but not found.
EXPECTED_NUM, //!< Occurred if a num is expected but not found.
WRONG_PLACED_SEPERATOR, //!< Occurred if a seprator is wrong placed.
MISSING_KEY, //!< Value found but key expected.
MISSING_VALUE, //!< Key found but value missing.
MISSING_SEPERATOR //!< Occurred if a ',' is missing before a key or ':' is missing before value.
};
/**
* @brief JSON value types.
*/
enum class JsonType
{
UNKNOWN,
NIL,
OBJECT,
ARRAY,
BOOLEAN,
INTEGER,
DOUBLE,
STRING
};
class CJSONException : public std::exception
{
public:
CJSONException() {}
CJSONException(JSONErrorType Type) : m_ErrType(Type) {}
CJSONException(const std::string &Msg, JSONErrorType Type) : m_Msg(Msg), m_ErrType(Type) {}
const char *what() const noexcept override
{
return m_Msg.c_str();
}
JSONErrorType GetErrType() const noexcept
{
return m_ErrType;
}
private:
std::string m_Msg;
JSONErrorType m_ErrType;
};
class CJSON
{
/**-----------------------------------------Blackmagic for SFINAE-----------------------------------------**/
//Concept from https://dev.krzaq.cc/post/checking-whether-a-class-has-a-member-function-with-a-given-signature/
template<class T>
struct has_push_back
{
private:
using Type = typename std::remove_pointer<T>::type;
template<class C> static auto Test(typename C::value_type *p) -> decltype(std::declval<C>().push_back(*p), std::true_type()) { return std::true_type(); }
template<class> static std::false_type Test(...) { return std::false_type(); }
public:
static const bool value = std::is_same<std::true_type, decltype(Test<Type>(nullptr))>::value;
};
template<class T>
struct has_push_front
{
private:
using Type = typename std::remove_pointer<T>::type;
template<class C> static auto Test(typename C::value_type *p) -> decltype(std::declval<C>().push_front(*p), std::true_type()) { return std::true_type(); }
template<class> static std::false_type Test(...) { return std::false_type(); }
public:
static const bool value = std::is_same<std::true_type, decltype(Test<Type>(nullptr))>::value;
};
template<class T>
struct has_begin_end
{
private:
using Type = typename std::remove_pointer<T>::type;
template<class C> static auto TestBegin(typename C::const_iterator *) -> decltype(static_cast<typename C::const_iterator>(std::declval<C>().begin()), std::true_type()) { return std::true_type(); }
template<class> static std::false_type TestBegin(...) { return std::false_type(); }
template<class C> static auto TestEnd(typename C::const_iterator *) -> decltype(static_cast<typename C::const_iterator>(std::declval<C>().end()), std::true_type()) { return std::true_type(); }
template<class> static std::false_type TestEnd(...) { return std::false_type(); }
public:
static const bool value = std::is_same<std::true_type, decltype(TestBegin<Type>(nullptr))>::value && std::is_same<std::true_type, decltype(TestEnd<Type>(nullptr))>::value;
};
template<class T>
struct is_map : std::false_type {};
template<class v>
struct is_map<std::map<std::string, v>> : std::true_type {};
template<class v>
struct is_map<std::unordered_map<std::string, v>> : std::true_type {};
template<class T>
struct is_multimap : std::false_type {};
template<class v>
struct is_multimap<std::multimap<std::string, v>> : std::true_type {};
template<class v>
struct is_multimap<std::unordered_multimap<std::string, v>> : std::true_type {};
template<class T>
struct is_shared_ptr : std::false_type {};
template<class T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template<class T>
struct is_pointer_type
{
static const bool value = std::is_pointer<T>::value || is_shared_ptr<T>::value;
};
template<class T>
struct pointer_type
{
using type = typename std::remove_pointer<T>::type;
};
template<class T>
struct pointer_type<std::shared_ptr<T>>
{
using type = T;
};
/**-----------------------------------------Blackmagic for SFINAE-----------------------------------------**/
public:
CJSON(/* args */) {}
/**
* @brief Serializes an object to a json object.
*
* To serialize an object you need to implement a serialize method.
* @code
* class YourClass
* {
* public:
* ...
* void Serialize(CJSON &json) const
* {
* ...
* json.AddPair("yourAttr", m_YourAttr); //Adds an attribute to the json object.
* ...
* }
* ...
* };
* @endcode
*
* @param obj: Object for serialization.
* @note This method handles only non-pointer objects, which are no STL containers.
*
* @return Returns a string which contains the json object.
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!is_pointer_type<T>::value && !has_begin_end<T>::value>::type* = nullptr>
inline std::string Serialize(const T &obj)
{
static_assert(std::is_class<T>::value, "Please use structs or objects!");
m_Values.clear();
obj.Serialize(*this);
return Serialize();
}
/**
* @brief Serializes STL container types except std::string, sets and queues.
*
* @param obj: Container for serialization.
* @note Theoretically you can serialize any container, which has an begin() and end() method who returns a const_iterator.
*
* @return Returns a json array.
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!is_pointer_type<T>::value && has_begin_end<T>::value && !std::is_same<T, std::string>::value>::type* = nullptr>
inline std::string Serialize(const T &obj)
{
m_Values.clear();
return ValueToString(obj);
}
/**
* @brief Serializes a pointer object to a json object.
*
* To serialize a pointer object you need to implement a serialize method.
* @code
* class YourClass
* {
* public:
* ...
* void Serialize(CJSON &json) const
* {
* ...
* json.AddPair("yourAttr", m_YourAttr); //Adds an attribute to the json object.
* ...
* }
* ...
* };
* @endcode
*
* @param obj: Object for serialization.
* @note This method handles only pointer objects or std::shared_ptr objects, which are no STL containers.
*
* @return Returns a string which contains the json object.
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<is_pointer_type<T>::value && !has_begin_end<T>::value>::type* = nullptr>
inline std::string Serialize(const T obj)
{
static_assert(std::is_class<typename std::remove_pointer<T>::type>::value, "Please use structs or objects!");
m_Values.clear();
obj->Serialize(*this);
return Serialize();
}
/**
* @brief Serializes the data which was added without an object.
*
* @return Returns a string which contains the json object.
*/
inline std::string Serialize()
{
std::string Ret;
for (auto &&e : m_Values)
{
if(!Ret.empty())
Ret += ',';
Ret += '"' + e.first + "\":" + e.second;
}
m_Values.clear();
return '{' + Ret + '}';
}
/**
* @brief Deserializes a json object to a already existing object.
*
* To deserialize a json object you need to implement a Deserialize method.
* @code
* class YourClass
* {
* public:
* ...
* void Deserialize(CJSON &json)
* {
* ...
* m_YourAttr = json.GetValue<std::string>("yourAttr"); //Gets the value of a json key.
* ...
* }
* ...
* };
* @endcode
*
* @param json: JSON for deserialization.
* @param Obj: Object wich will receive the data.
*
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!is_map<T>::value && !is_multimap<T>::value && !has_begin_end<T>::value>::type* = nullptr>
inline void Deserialize(const std::string &json, T *Obj)
{
static_assert(std::is_class<typename pointer_type<T>::type>::value, "Please use structs or objects!");
ParseObject(json);
Obj->Deserialize(*this);
m_Values.clear();
}
/**
* @brief Deserializes a json object to a pointer object.
*
* To deserialize a json object you need to implement a Deserialize method, also you need a standard constructor.
* @code
* class YourClass
* {
* public:
* YourClass() {} //<- Necessary
*
* ...
* void Deserialize(CJSON &json)
* {
* ...
* m_YourAttr = json.GetValue<std::string>("yourAttr"); //Gets the value of a json key.
* ...
* }
* ...
* };
* @endcode
*
* @param json: JSON for deserialization.
* @note This method returns only pointer objects or std::shared_ptr objects.
*
* @return Returns a new object.
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<is_pointer_type<T>::value && !is_map<T>::value && !is_multimap<T>::value && !has_begin_end<T>::value>::type* = nullptr>
inline T Deserialize(const std::string &json)
{
static_assert(std::is_class<typename pointer_type<T>::type>::value, "Please use structs or objects!");
ParseObject(json);
T ret = CreatePointer<T>();
ret->Deserialize(*this);
m_Values.clear();
return ret;
}
/**
* @brief Deserializes a json object to a object.
*
* To deserialize a json object you need to implement a Deserialize method, also you need a standard constructor.
* @code
* class YourClass
* {
* public:
* YourClass() {} //<- Necessary
*
* ...
* void Deserialize(CJSON &json)
* {
* ...
* m_YourAttr = json.GetValue<std::string>("yourAttr"); //Gets the value of a json key.
* ...
* }
* ...
* };
* @endcode
*
* @param json: JSON for deserialization.
* @note This method returns only objects.
*
* @return Returns a new object.
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!is_pointer_type<T>::value && !is_map<T>::value && !is_multimap<T>::value && !has_begin_end<T>::value>::type* = nullptr>
inline T Deserialize(const std::string &json)
{
static_assert(std::is_class<T>::value, "Please use structs or objects!");
ParseObject(json);
T ret;
ret.Deserialize(*this);
m_Values.clear();
return ret;
}
/**
* @brief Deserializes to map types.
*
* @param json: JSON for deserialization.
* @return Returns a new map type.
*
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!is_pointer_type<T>::value && is_map<T>::value>::type* = nullptr>
inline T Deserialize(const std::string &json)
{
static_assert(std::is_class<T>::value, "Please use structs or objects!");
ParseObject(json);
T Ret;
for (auto &&e : m_Values)
Ret[e.first] = ParseValue<typename T::mapped_type>(e.second);
m_Values.clear();
return Ret;
}
/**
* @brief Deserializes to multimap types.
*
* @param json: JSON for deserialization.
* @return Returns a new multimap type.
*
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!is_pointer_type<T>::value && is_multimap<T>::value>::type* = nullptr>
inline T Deserialize(const std::string &json)
{
static_assert(std::is_class<T>::value, "Please use structs or objects!");
ParseObject(json);
T Ret;
for (auto &&e : m_Values)
{
std::vector<typename T::mapped_type> arr = ParseValue<std::vector<typename T::mapped_type>>(e.second);
for(auto &&ae : arr)
Ret.insert(std::pair<typename T::key_type, typename T::mapped_type>(e.first, ae));
}
m_Values.clear();
return Ret;
}
/**
* @brief Deserializes to all STL containers, which implements the push_back() or push_front() method.
*
* @param json: JSON for deserialization.
* @note Theoretically you can deserialize any container which implements these methods.
* @return Returns a new container.
*
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!is_pointer_type<T>::value && !is_map<T>::value && !is_multimap<T>::value && has_begin_end<T>::value>::type* = nullptr>
inline T Deserialize(const std::string &json)
{
static_assert(std::is_class<T>::value, "Please use structs or objects!");
return ParseValue<T>(json);
}
/**
* @brief Parses a given json object.
*
* @param obj: JSON object string.
* @note You can access each value via @see GetValue.
*
* @throw CJSONException If any error occurres.
*/
inline void ParseObject(const std::string &obj)
{
m_Values.clear();
std::string Key, Value;
bool ValAllowed = false;
bool KeyValueValid = false;
bool ValidObject = false;
/*
Why we use raw pointers instead of iterators or an for loop?
Because I think its much faster to use pointer arithmetic instead
of iterator arithmetic or for loops.
If I'm wrong with my thoughts, please correct me.
*/
const char *beg = obj.c_str();
const char *end = beg + obj.size();
while (beg != end && *beg != '}')
{
switch (*beg)
{
// Parses a string.
case '\"':
{
// Throw an exception if we found a string outside of an object.
if(!ValidObject)
throw CJSONException(JSONErrorType::INVALID_JSON_OBJECT);
else if(KeyValueValid)
throw CJSONException("Missing seperator ','.", JSONErrorType::MISSING_SEPERATOR);
// Quick and dirty check if we need a key or a value.
if(Key.empty())
Key = ParseString(beg, end);
else if(Value.empty() && ValAllowed)
{
ValAllowed = false;
KeyValueValid = true;
Value = ParseString(beg, end);
}
else // Throw an exception if we doesn't expected a key or value. That occurs always if a colon is missing.
throw CJSONException("Missing seperator after '" + Key + "'", JSONErrorType::MISSING_SEPERATOR);
}break;
// Ignore all whitespace characters, which are outside of values.
case '\t':
case '\n':
case '\f':
case '\r':
case ' ':
{
}break;
// Parses an object or array.
case '{':
case '[':
{
// If this is the root object then set the validator flag.
if(!ValidObject)
{
ValidObject = true;
break;
}
// Throws an exception either if the key is missing or a value wasn't expected.
if(Key.empty())
throw CJSONException(JSONErrorType::MISSING_KEY);
else if(!ValAllowed)
throw CJSONException("Missing seperator after '" + Key + "'", JSONErrorType::MISSING_SEPERATOR);
ValAllowed = false;
KeyValueValid = true;
// Objects and arrays are saved as strings and parsed later.
if(*beg == '{')
Value = ParseBracketStr('{', '}', beg, end);
else if(*beg == '[')
Value = ParseBracketStr('[', ']', beg, end);
}break;
// Allows the next key value pair.
case ',':
{
if(!ValidObject)
throw CJSONException(JSONErrorType::INVALID_JSON_OBJECT);
if(!KeyValueValid)
throw CJSONException("Lonly ','", JSONErrorType::WRONG_PLACED_SEPERATOR);
KeyValueValid = false;
}break;
// Allows a value.
case ':':
{
if(!ValidObject)
throw CJSONException(JSONErrorType::INVALID_JSON_OBJECT);
if(Key.empty())
throw CJSONException(JSONErrorType::MISSING_KEY);
ValAllowed = true;
}break;
default:
{
if(!ValidObject)
throw CJSONException(JSONErrorType::INVALID_JSON_OBJECT);
if(Key.empty())
throw CJSONException(JSONErrorType::MISSING_KEY);
else if(!ValAllowed)
throw CJSONException("Missing seperator after '" + Key + "'", JSONErrorType::MISSING_SEPERATOR);
ValAllowed = false;
KeyValueValid = true;
switch (*beg)
{
// If a non escaped string begins with t or f it's maybe a boolean.
case 't':
case 'f':
{
Value = ParseBool(beg, end);
}break;
// If a non escaped string begins with n it's maybe a null object.
case 'n':
{
Value = ParseNull(beg, end);
}break;
default:
{
// If a non escaped string begins with a number, plus or minus it's maybe a number.
if(isalnum(*beg) || *beg == '-' || *beg == '+')
Value = ParseNum(beg, end);
else // Otherwise throw an exception.
throw CJSONException("Invalid type for key '" + Key + "'", JSONErrorType::INVALID_TYPE);
}break;
}
}break;
}
// If key and value is set save it for later use.
if(KeyValueValid)
{
ValAllowed = false;
m_Values[Key] = Value;
Key.clear();
Value.clear();
}
if(beg != end)
beg++;
}
// Validates the object.
if(ValidObject && *beg != '}')
throw CJSONException(JSONErrorType::INVALID_JSON_OBJECT);
}
/**
* @brief Adds a new value to the json.
*
* @param Name: Name of the value in the json file.
* @param val: Value of the json value.
* @param IsObjectStr: Value is already an json object.
*
* @note You can add any type. It can be primitive, pointer, object or container types. The object type need to implement the Serialize method.
* @throw CJSONException If any error occurres.
*/
template<class T>
inline void AddPair(const std::string &Name, const T &val)
{
if(m_Values.find(Name) != m_Values.end())
throw CJSONException("Name '" + Name + "' already exists!", JSONErrorType::NAME_ALREADY_EXITS);
m_Values[Name] = ValueToString(val);
}
/**
* @brief Adds a new value to the json.
*
* @param Name: Name of the value in the json file.
* @param val: Value of the json value.
*
* @note You can add any type. It can be primitive, pointer, object or container types. The object type need to implement the Serialize method.
* @throw CJSONException If any error occurres.
*/
inline void AddJSON(const std::string &Name, const std::string &val)
{
if(m_Values.find(Name) != m_Values.end())
throw CJSONException("Name '" + Name + "' already exists!", JSONErrorType::NAME_ALREADY_EXITS);
m_Values[Name] = val;
}
/**
* @brief Adds a new primitive array to the json.
*
* @param Name: Name of the array in the json file.
* @param val: Value of the json array.
* @param Size: Size of the array.
*
* @note You can add any type. It can be primitive or object array types. The object type need to implement the Serialize method.
* @throw CJSONException If any error occurres.
*/
template<class T>
inline void AddPair(const std::string &Name, const T &val, size_t Size)
{
if(m_Values.find(Name) != m_Values.end())
throw CJSONException("Name '" + Name + "' already exists!", JSONErrorType::NAME_ALREADY_EXITS);
m_Values[Name] = '[' + ArrayToStr(val, Size) + ']';
}
/**
* @return Gets the type of the value.
*/
inline JsonType GetType(const std::string &Key)
{
auto IT = m_Values.find(Key);
if(IT == m_Values.end())
throw CJSONException("Name '" + Key + "' not found", JSONErrorType::NAME_NOT_FOUND);
if(IT->second == "null")
return JsonType::NIL;
else if(IT->second == "true" || IT->second == "false")
return JsonType::BOOLEAN;
else if(IT->second[0] == '{') //Quick and dirty check.
return JsonType::OBJECT;
else if(IT->second[0] == '[') //Quick and dirty check.
return JsonType::ARRAY;
else if(IT->second[0] == '\"') //Quick and dirty check.
return JsonType::STRING;
if(IT->second.find("."))
{
try
{
std::stod(IT->second); //Quick and dirty check.
return JsonType::DOUBLE;
}
catch(const std::exception& e)
{
return JsonType::UNKNOWN;
}
}
else
{
try
{
std::stoi(IT->second); //Quick and dirty check.
return JsonType::INTEGER;
}
catch(const std::exception& e)
{
return JsonType::UNKNOWN;
}
}
}
/**
* @return Returns true if the given key exists.
*/
inline bool HasKey(const std::string &Key)
{
return m_Values.find(Key) != m_Values.end();
}
/**
* @brief Gets the value for a given name.
*
* @param Name: Name of the value.
* @param Default: Default value if the given value doesn't exists.
*
* @note For primitive, pointer, std::string and container types.
*
* @return Returns the requested value.
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<!std::is_class<typename std::remove_pointer<T>::type>::value || std::is_same<T, std::string>::value || has_push_back<T>::value>::type* = nullptr>
T GetValue(const std::string &Name, const T &Default = T())
{
std::map<std::string, std::string>::iterator IT = m_Values.find(Name);
if(IT == m_Values.end())
return Default;
if(IT->second == "null")
return AddNullObj<T>();
return ParseValue<T>(IT->second);
}
/**
* @brief Gets the value for a given name.
*
* @param Name: Name of the value.
*
* @note For objects.
*
* @return Returns the requested object.
* @throw CJSONException If any error occurres.
*/
template<class T, typename std::enable_if<std::is_class<typename pointer_type<T>::type>::value && !std::is_same<T, std::string>::value && !has_push_back<T>::value>::type* = nullptr>
T GetValue(const std::string &Name)
{
std::map<std::string, std::string>::iterator IT = m_Values.find(Name);
if(IT == m_Values.end())
throw CJSONException("Name '" + Name + "' not found", JSONErrorType::NAME_NOT_FOUND);
if(IT->second == "null")
return AddNullObj<T>();
CJSON json;
return json.Deserialize<T>(IT->second);
}
/**
* @brief Gets the value for a given array.
*
* @param Name: Name of the array.
* @param[out] Size: The size of the array.
*
* @return Returns a primitive array.
* @throw CJSONException If any error occurres.
*/
template<class T>
T GetValue(const std::string &Name, size_t &Size)
{
std::map<std::string, std::string>::iterator IT = m_Values.find(Name);
if(IT == m_Values.end())
{
Size = 0;
return nullptr;
}
if(IT->second == "null")
{
Size = 0;
return AddNullObj<T>();
}
return ParseArray<T>(IT->second, Size);
}
~CJSON() {}
private:
std::map<std::string, std::string> m_Values;
/**-----------------------------------------Blackmagic for SFINAE-----------------------------------------**/
/** Creates a std::shared_ptr **/
template<class T, typename std::enable_if<is_shared_ptr<T>::value>::type* = nullptr>
inline T CreatePointer()
{
return T(new typename pointer_type<T>::type());
}
/** Creates a primitive pointer **/
template<class T, typename std::enable_if<std::is_pointer<T>::value>::type* = nullptr>
inline T CreatePointer()
{
return new typename pointer_type<T>::type();
}
// Validates the json bool.
inline std::string ParseBool(const char *&beg, const char *&end)
{
std::string Ret;
while (beg != end)
{
if(*beg == ',' || *beg == '}' || *beg == ']')
break;
Ret += *beg;
beg++;
}
beg--;
if(Ret != "true" && Ret != "false")
throw CJSONException("Expected bool", JSONErrorType::EXPECTED_BOOL);
return Ret;
}
// Validates the json null object.
inline std::string ParseNull(const char *&beg, const char *&end)
{
std::string Ret;
while (beg != end)
{
if(*beg == ',' || *beg == '}' || *beg == ']')
break;
Ret += *beg;
beg++;
}
beg--;
if(Ret != "null")
throw CJSONException("Expected null", JSONErrorType::EXPECTED_NULL);
return Ret;
}
// Validates the json number.
inline std::string ParseNum(const char *&beg, const char *&end)
{
std::string Ret;
while (beg != end)
{
if(*beg == ',' || *beg == '}' || *beg == ']')
break;
Ret += *beg;
beg++;
}
beg--;
try
{
std::stod(Ret);
}
catch(const std::exception& e)
{
throw CJSONException("Expected number", JSONErrorType::EXPECTED_NUM);
}
return Ret;
}
/**
* Groups all characters from OpenBracket to CloseBracket into a single string.
* This is used for objects and arrays.
*/
inline std::string ParseBracketStr(char OpenBracket, char CloseBracket, const char *&beg, const char *&end)
{
std::string Ret;
int OpenBrackets = 0;
while (beg != end)
{
Ret += *beg;
// Counts the numbers of found open brackets. This is used to determine the end of the string.
if(*beg == OpenBracket)
OpenBrackets++;
else if(*beg == CloseBracket)
OpenBrackets--;
if(OpenBrackets == 0)
break;
beg++;
}
return Ret;
}
// Parses a json string and return the unescaped string.
inline std::string ParseString(const char *&beg, const char *&end)
{
std::string Ret;
bool EscapeFound = false;
beg++;
while (beg != end)
{
if(*beg == '\"' && !EscapeFound)
break;
Ret += *beg;
if(*beg == '\\')
EscapeFound = true;
else if(EscapeFound && *beg != '\\')
EscapeFound = false;
beg++;
}
return UnescapeString(Ret);
}
inline int IsUTF8(unsigned char c)
{
if((c & 0xF0) == 0xF0)
return 3;
if((c & 0xE0) == 0xE0)
return 2;
if((c & 0xC0) == 0xC0)
return 1;
return 0;
}
inline int UTF8BitShift(unsigned char c)
{
if((c & 0xF0) == 0xF0)
return 5;
if((c & 0xE0) == 0xE0)
return 4;
if((c & 0xC0) == 0xC0)
return 3;
if((c & 0x80) == 0x80)
return 2;
return 0;