-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDelphiJSON.pas
More file actions
2527 lines (2178 loc) · 66.7 KB
/
DelphiJSON.pas
File metadata and controls
2527 lines (2178 loc) · 66.7 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
///
/// DelphiJSON Library - Copyright (c) 2020 Corbinian Gruber
///
/// Version: 1.0.0
///
/// This library is licensed under the MIT License.
/// https://github.com/gruco0002/DelphiJSON
///
unit DelphiJSON;
interface
uses
System.SysUtils, System.JSON, System.RTTI, System.Generics.Collections;
type
/// <summary>
/// Defines settings for the (de)serialization.
/// </summary>
TDJSettings = class
public
/// <summary>
/// Determines if the [DJSerializableAttribute] is needed as annotation for classes / records.
/// The default is true.
/// It is not recommended to set the value to false.
/// Most serializable RTL classes / records are not affected by this.
/// </summary>
RequireSerializableAttributeForNonRTLClasses: Boolean;
/// <summary>
/// Determines if the date time (de)serialization assumes that the Delphi
/// value stored in a TDateTime object is considered to be UTC time.
/// The default is true.
/// More information can be found in the RTL documentation for [System.DateUtils.DateToISO8601]
/// </summary>
DateTimeReturnUTC: Boolean;
/// <summary>
/// Makes the (de)serializer ignore all [DJNonNilableAttribute] annotations.
/// This can be used if values are allowed to be nil during serialization,
/// but not during deserialization.
/// It only affects fields annotated with [DJNonNilableAttribute].
/// The default is false.
/// </summary>
IgnoreNonNillable: Boolean;
/// <summary>
/// If set to true, makes all fields required. If set to false all fields are optional.
/// This has only an effect during deserialization.
/// The default value if true.
/// This value is ignored if a field is annotated with the [DJRequiredAttribute].
/// A required field that is not present in a JSON object causes an
/// [EDJRequiredError] exception during deserialization.
/// If a field is not required, it has not to be present in the JSON object.
/// In this case the delphi field is not set to anything or a default value
/// if either the [DJDefaultValueAttribute] or the [DJDefaultValueCreatorAttribute] is present.
/// </summary>
RequiredByDefault: Boolean;
/// <summary>
/// If set to true, the (de)serializer assumes that TDictionary's that have
/// string set as their key type are represented by JSON objects and
/// (de)serializes them respectively. If set to false, those TDictionary's
/// will be (de)serialized like other dictionaries (to/from a JSON array of
/// key-value objects).
/// The default value is true.
/// </summary>
TreatStringDictionaryAsObject: Boolean;
/// <summary>
/// If set to true, the deserializer ignores fields in the JSON data, that
/// are not used for deserialization (that have no counterpart in the delphi
/// data representation). If set to false the deserialization raises an
/// exception upon encountering unused fields.
/// The default value is true.
/// This value is ignored for a class or record if it is annotated with the
/// [DJNoUnusedJSONFieldsAttribute].
/// </summary>
AllowUnusedJSONFields: Boolean;
/// <summary>
/// Creates the default settings for (de)serialization.
/// </summary>
constructor Default;
end;
/// <summary>
/// Static class that has functions for (de)serializing.
/// Note: always specify the correct type for [T]. Wrong types could lead to
/// undefined behaviour.
/// An instance of this class must not be created.
/// </summary>
DelphiJSON<T> = class
public
/// <summary>
/// Deserializes the JSON string [data] into the specified object type.
/// Optional settings can be given with the [settings] argument.
/// If [settings] are given they are not freed by the function.
/// If the deserialization causes an error this function will throw this
/// error after an internal cleanup to avoid memory leaks.
/// Note: always specify the correct type for [T]. Wrong types could lead to
/// undefined behaviour.
/// </summary>
class function Deserialize(data: String; settings: TDJSettings = nil): T;
/// <summary>
/// Deserializes the JSON value [data] into the specified object type.
/// The given value [data] is not freed by the function.
/// Optional settings can be given with the [settings] argument.
/// If [settings] are given they are not freed by the function.
/// If the deserialization causes an error this function will throw this
/// error after an internal cleanup to avoid memory leaks.
/// Note: always specify the correct type for [T]. Wrong types could lead to
/// undefined behaviour.
/// </summary>
class function DeserializeJ(data: TJSONValue; settings: TDJSettings = nil): T;
/// <summary>
/// Serializes the given [data] into a JSON string.
/// The [data] is not freed by the function.
/// Optional settings can be given with the [settings] argument.
/// If [settings] are given they are not freed by the function.
/// If the serialization causes an error this function will throw this
/// error after an internal cleanup to avoid memory leaks.
/// Note: always specify the correct type for [T]. Wrong types could lead to
/// undefined behaviour.
/// </summary>
class function Serialize(data: T; settings: TDJSettings = nil): string;
/// <summary>
/// Serializes the given [data] into a JSON value.
/// The [data] is not freed by the function.
/// Optional settings can be given with the [settings] argument.
/// If [settings] are given they are not freed by the function.
/// If the serialization causes an error this function will throw this
/// error after an internal cleanup to avoid memory leaks.
/// The resources (JSON Values) are not managed by the serializer and belong
/// to the caller of the function after it returns!
/// Note: always specify the correct type for [T]. Wrong types could lead to
/// undefined behaviour.
/// </summary>
class function SerializeJ(data: T; settings: TDJSettings = nil): TJSONValue;
private
constructor Create;
end;
/// <summary>
/// Makes a field (de)serializable and specifies its JSON name.
/// All fields that are not annotated with this attribute are ignored during
/// the (de)serialization.
/// The name has to be unique for an object.
/// </summary>
DJValueAttribute = class(TCustomAttribute)
public
Name: string;
constructor Create(const Name: string);
end;
/// <summary>
/// Makes a class or record (de)serializable.
/// This attribute is needed to explicitly state that a class / record is serializable.
/// </summary>
DJSerializableAttribute = class(TCustomAttribute)
end;
/// <summary>
/// Makes the annotated field non nillable.
/// During (de)serialization a nil/null value for this field would cause an [EDJNilError].
/// This behaviour can be overwritten by the [IgnoreNonNillable] property of the [TDJSettings].
/// </summary>
DJNonNilableAttribute = class(TCustomAttribute)
end;
/// <summary>
/// Makes the annotated constructor the default constructor that is used for deserialization.
/// The constructor must not have any arguments.
/// If no constructor is annotated the Create constructor will be used (if it does not require any arguments)
/// </summary>
DJConstructorAttribute = class(TCustomAttribute)
end;
/// <summary>
/// Internal interface used for default values.
/// </summary>
IDJDefaultValue = class(TCustomAttribute)
protected
function GetValue: TValue; virtual; abstract;
end;
/// <summary>
/// Defines a default value for a field that is used during deserialization.
/// The default value is used if the field is not defined in the given JSON object.
/// This attribute only supports primitive values.
/// This attribute has no effect if not used together with either the [DJDefaultOnNilAttribute] or the [DJRequiredAttribute].
/// </summary>
DJDefaultValueAttribute = class(IDJDefaultValue)
private
value: TValue;
protected
function GetValue: TValue; override;
public
constructor Create(const value: string); overload;
constructor Create(const value: integer); overload;
constructor Create(const value: single); overload;
constructor Create(const value: double); overload;
constructor Create(const value: Boolean); overload;
constructor Create(const value: TValue); overload;
end;
/// <summary>
/// Defines an abstract generator for a default value for a field that is used
/// during deserialization. To use the attribute, derive a custom non generic
/// generator that implementes the [Generator] function and annotate the
/// appropriate field.
/// Be sure to use the correct type [T].
/// The default value is used if the field is not defined in the given JSON object.
/// The generator is called during the deserialization.
/// This attribute has no effect if not used together with either the [DJDefaultOnNilAttribute] or the [DJRequiredAttribute].
/// </summary>
DJDefaultValueCreatorAttribute<T> = class(IDJDefaultValue)
protected
function GetValue: TValue; override; final;
public
function Generator: T; virtual; abstract;
end;
/// <summary>
/// Makes the field use the default value if it has the value nil / null during deserialization.
/// This attribute has only an effect if used together with one of the default
/// value attributes [DJDefaultValueCreatorAttribute] or [DJDefaultValueAttribute]
/// </summary>
DJDefaultOnNilAttribute = class(TCustomAttribute)
end;
/// <summary>
/// Makes a field required if [required] is true and optional if [required] is false.
/// The default value is true. This attribute only affects the deserialization.
/// This overrides the settings given by the [DJSettings] object for the annotated field.
/// If a required field is not specified in the JSON object an [EDJRequiredError] is thrown.
/// Note that nil/null values for a field do not raise an exception, since the field is
/// existing in the JSON object (See [DJNonNilableAttribute] for that case)
/// </summary>
DJRequiredAttribute = class(TCustomAttribute)
public
required: Boolean;
constructor Create(const required: Boolean = True);
end;
/// <summary>
/// Internal interface used for converters.
/// </summary>
IDJConverterInterface = class(TCustomAttribute)
protected
function ToJSONinternal(value: TValue): TJSONValue; virtual; abstract;
function FromJSONinternal(value: TJSONValue): TValue; virtual; abstract;
end;
/// <summary>
/// Abstract converter attribute used to implement custom converters.
/// Custom converters are implemented by the user by overriding the [ToJSON]
/// and [FromJSON] functions.
/// The custom converter is then used as an attribute to annotate the fields
/// that should be (de)serialized using the converter.
/// It is not required to implement both functions as the [ToJSON] function
/// is only called during serialization and the [FromJSON] function is only
/// called during deserialization.
/// Converters are called instead of the normal (de)serialization for the
/// given value.
/// All other attributes of the annotated field are evaluated before the
/// converter is called.
/// </summary>
DJConverterAttribute<T> = class(IDJConverterInterface)
protected
function ToJSONinternal(value: TValue): TJSONValue; override;
function FromJSONinternal(value: TJSONValue): TValue; override;
public
function ToJSON(value: T): TJSONValue; virtual; abstract;
function FromJSON(value: TJSONValue): T; virtual; abstract;
end;
/// <summary>
/// Makes a class or record raise an error on deserialization if there are
/// fields in the JSON data, that are not explicitly mapped to a field in the
/// class or record (iff [noUnusedFields] is set to true).
/// If the [noUnusedFields] is set to false, such additional JSON fields are
/// ignored and no errors are raised
/// Overrides the [AllowUnusedJSONFields] setting for the annotated class or
/// record.
/// </summary>
DJNoUnusedJSONFieldsAttribute = class(TCustomAttribute)
public
noUnusedFields: Boolean;
constructor Create(const noUnusedFields: Boolean = True);
end;
/// <summary>
/// If applied to a field the [DJNullIfEmptyAttribute] is active during
/// serialization and causes an empty [string] to be represented by the
/// JSON null literal instead of an empty JSON string literal. ///
/// </summary>
DJNullIfEmptyStringAttribute = class(TCustomAttribute)
end;
TSerContext = class;
/// <summary>
/// Describes an error that happened during deserialization.
/// </summary>
EDJError = class(Exception)
public
path: TList<String>;
errorMessage: String;
constructor Create(errorMessage: String; context: TSerContext); overload;
function Clone: EDJError; virtual;
destructor Destroy; override;
function FullPath: string;
private
constructor Create(errorMessage: String;
const path: TList<String>); overload;
end;
/// <summary>
/// This error is raised if an required field is not found in the JSON object.
/// </summary>
EDJRequiredError = class(EDJError)
public
function Clone: EDJError; override;
end;
/// <summary>
/// This error is raised if a field is nil/null although it is annotated with
/// the [DJNonNilableAttribute].
/// </summary>
EDJNilError = class(EDJError)
public
function Clone: EDJError; override;
end;
/// <summary>
/// This error is raised if a fixed sized array is being deserialized and the
/// size of the array in the JSON data does not match the delphi fixed array
/// size.
/// </summary>
EDJWrongArraySizeError = class(EDJError)
public
function Clone: EDJError; override;
end;
/// <summary>
/// This error is raised if a reference cycle during serialization is
/// detected.
/// A reference cycle can occur if fields that are serialized point towards
/// objects that have already been serialized or are in the process of being
/// serialized.
/// </summary>
EDJCycleError = class(EDJError)
public
function Clone: EDJError; override;
end;
/// <summary>
/// This error is raised if unused fields are discovered in the JSON data
/// during the deserialization and such fields are not allowed.
/// See the [DJNoUnusedJSONFieldsAttribute] or the [AllowUnusedJSONFields]
/// property of the [TDJSettings] for more information.
/// </summary>
EDJUnusedFieldsError = class(EDJError)
public
function Clone: EDJError; override;
end;
/// <summary>
/// This error is raised if a wrong format of the JSON data is provided during
/// deserialization.
/// E.g.: A DateTime string should be deserialized but does not meet the
/// requirement of the ISO 8601 format.
/// </summary>
EDJFormatError = class(EDJError)
public
function Clone: EDJError; override;
end;
TSerContext = class
private
path: TStack<string>;
// keeps track of heap allocated objects in order to free them, if an error happens and no value can be returned
// this is implemented to avoid memory leaks through invalid json or parameters / other issues
heapAllocatedObjects: TDictionary<TObject, Boolean>;
// used to detect cycles during serialization
objectTracker: TDictionary<TObject, Boolean>;
procedure NilAllReferencesRecursive(value: TValue);
public
RTTI: TRttiContext;
settings: TDJSettings;
constructor Create;
destructor Destroy; override;
function FullPath: string;
procedure PushPath(val: string); overload;
procedure PushPath(index: integer); overload;
procedure PopPath;
procedure AddHeapObject(obj: TObject);
procedure RemoveHeapObject(obj: TObject);
procedure FreeAllHeapObjects;
procedure Track(obj: TObject);
function IsTracked(obj: TObject): Boolean;
function ToString: string; override;
end;
TDerContext = TSerContext;
function SerializeInternal(value: TValue; context: TSerContext; nullIfEmptyString: Boolean = false): TJSONValue;
function DeserializeInternal(value: TJSONValue; dataType: TRttiType;
context: TDerContext): TValue;
implementation
uses
System.TypInfo, System.DateUtils;
var
unitRttiContextInstance: TRttiContext;
function PathToString(path: TEnumerable<String>): String;
var
ele: String;
begin
Result := '';
for ele in path do
begin
if Result.Length = 0 then
begin
Result := ele;
end
else
begin
Result := Result + '>' + ele;
end;
end;
end;
function SerArray(value: TValue; context: TSerContext): TJSONArray;
var
size: integer;
i: integer;
tmp: TJSONValue;
begin
Result := TJSONArray.Create;
context.AddHeapObject(Result);
size := value.GetArrayLength;
for i := 0 to size - 1 do
begin
context.PushPath(i.ToString);
tmp := SerializeInternal(value.GetArrayElement(i), context);
context.RemoveHeapObject(tmp);
Result.AddElement(tmp);
context.PopPath;
end;
end;
function SerFloat(value: TValue; context: TSerContext): TJSONNumber;
begin
Result := TJSONNumber.Create(value.AsType<single>());
context.AddHeapObject(Result);
end;
function SerInt64(value: TValue; context: TSerContext): TJSONNumber;
begin
Result := TJSONNumber.Create(value.AsInt64);
context.AddHeapObject(Result);
end;
function SerInt(value: TValue; context: TSerContext): TJSONNumber;
begin
Result := TJSONNumber.Create(value.AsInteger);
context.AddHeapObject(Result);
end;
function SerString(value: TValue; context: TSerContext; nullIfEmptyString: Boolean): TJSONValue;
begin
if nullIfEmptyString then
begin
if value.AsString.IsEmpty then
begin
Result := TJSONNull.Create;
context.AddHeapObject(Result);
exit;
end;
end;
Result := TJSONString.Create(value.AsString);
context.AddHeapObject(Result);
end;
function SerTEnumerable(data: TObject; dataType: TRttiType;
context: TSerContext): TJSONArray;
var
getEnumerator: TRttiMethod;
enumerator: TValue;
moveNext: TRttiMethod;
currentProperty: TRttiProperty;
currentValue: TValue;
currentSerialized: TJSONValue;
moveNextValue: TValue;
moveNextResult: Boolean;
i: integer;
begin
// idea: fetch enumerator with rtti, enumerate using movenext, adding objects
// to the array
getEnumerator := dataType.GetMethod('GetEnumerator');
enumerator := getEnumerator.Invoke(data, []);
moveNext := getEnumerator.ReturnType.GetMethod('MoveNext');
currentProperty := getEnumerator.ReturnType.GetProperty('Current');
Result := TJSONArray.Create;
context.AddHeapObject(Result);
// inital move
moveNextValue := moveNext.Invoke(enumerator.AsObject, []);
moveNextResult := moveNextValue.AsBoolean;
i := 0;
while moveNextResult do
begin
// retrieve current object
currentValue := currentProperty.GetValue(enumerator.AsObject);
// serialize it and add it to the result
context.PushPath(i.ToString);
currentSerialized := SerializeInternal(currentValue, context);
context.PopPath;
context.RemoveHeapObject(currentSerialized);
Result.AddElement(currentSerialized);
// move to the next object
moveNextValue := moveNext.Invoke(enumerator.AsObject, []);
moveNextResult := moveNextValue.AsBoolean;
Inc(i);
end;
enumerator.AsObject.Free;
end;
function SerTDictionaryStringKey(data: TObject; dataType: TRttiType;
context: TSerContext): TJSONObject;
var
getEnumerator: TRttiMethod;
enumerator: TValue;
moveNext: TRttiMethod;
currentProperty: TRttiProperty;
currentPairValue: TValue;
keyField: TRttiField;
valueField: TRttiField;
keyValue: TValue;
valueValue: TValue;
keyString: string;
serializedValue: TJSONValue;
moveNextValue: TValue;
moveNextResult: Boolean;
begin
// idea: the string keys are used as object field names and the values form
// the respective field value
getEnumerator := dataType.GetMethod('GetEnumerator');
enumerator := getEnumerator.Invoke(data, []);
moveNext := getEnumerator.ReturnType.GetMethod('MoveNext');
currentProperty := getEnumerator.ReturnType.GetProperty('Current');
keyField := currentProperty.PropertyType.GetField('Key');
valueField := currentProperty.PropertyType.GetField('Value');
Result := TJSONObject.Create;
context.AddHeapObject(Result);
// inital move
moveNextValue := moveNext.Invoke(enumerator.AsObject, []);
moveNextResult := moveNextValue.AsBoolean;
while moveNextResult do
begin
// retrieve current pair
currentPairValue := currentProperty.GetValue(enumerator.AsObject);
keyValue := keyField.GetValue(currentPairValue.GetReferenceToRawData);
valueValue := valueField.GetValue(currentPairValue.GetReferenceToRawData);
keyString := keyValue.AsString;
context.PushPath(keyString);
serializedValue := SerializeInternal(valueValue, context);
context.PopPath;
context.RemoveHeapObject(serializedValue);
Result.AddPair(keyString, serializedValue);
// move to the next object
moveNextValue := moveNext.Invoke(enumerator.AsObject, []);
moveNextResult := moveNextValue.AsBoolean;
end;
enumerator.AsObject.Free;
end;
function SerTPair(data: TValue; dataType: TRttiType; context: TSerContext)
: TJSONObject;
var
keyField: TRttiField;
valueField: TRttiField;
keyValue: TValue;
valueValue: TValue;
serializedKey: TJSONValue;
serializedValue: TJSONValue;
begin
keyField := dataType.GetField('Key');
valueField := dataType.GetField('Value');
keyValue := keyField.GetValue(data.GetReferenceToRawData);
valueValue := valueField.GetValue(data.GetReferenceToRawData);
context.PushPath('key');
serializedKey := SerializeInternal(keyValue, context);
context.PopPath;
context.PushPath('value');
serializedValue := SerializeInternal(valueValue, context);
context.PopPath;
Result := TJSONObject.Create;
context.AddHeapObject(Result);
context.RemoveHeapObject(serializedKey);
Result.AddPair('key', serializedKey);
context.RemoveHeapObject(serializedValue);
Result.AddPair('value', serializedValue);
end;
function SerTDateTime(data: TValue; dataType: TRttiType; context: TSerContext)
: TJSONString;
var
dt: TDateTime;
str: string;
begin
dt := data.AsType<TDateTime>();
str := DateToISO8601(dt, context.settings.DateTimeReturnUTC);
Result := TJSONString.Create(str);
context.AddHeapObject(Result);
end;
function SerTDate(data: TValue; dataType: TRttiType; context: TSerContext)
: TJSONString;
const
format = 'yyyy-mm-dd';
var
dt: TDate;
str: string;
begin
dt := data.AsType<TDate>();
DateTimeToString(str, format, dt);
Result := TJSONString.Create(str);
context.AddHeapObject(Result);
end;
function SerTTime(data: TValue; dataType: TRttiType; context: TSerContext)
: TJSONString;
const
format = 'hh:nn:ss.z';
var
dt: TTime;
str: string;
begin
dt := data.AsType<TTime>();
DateTimeToString(str, format, dt);
Result := TJSONString.Create(str);
context.AddHeapObject(Result);
end;
function SerTJSONValue(data: TValue; dataType: TRttiType; context: TSerContext)
: TJSONValue;
var
original: TJSONValue;
begin
original := data.AsType<TJSONValue>();
Result := original.Clone as TJSONValue;
context.AddHeapObject(Result);
end;
function SerHandledSpecialCase(data: TValue; dataType: TRttiType;
var output: TJSONValue; context: TSerContext): Boolean;
var
tmp: TRttiType;
begin
tmp := dataType;
while tmp <> nil do
begin
if tmp.Name.ToLower = 'tdatetime' then
begin
Result := True;
output := SerTDateTime(data, dataType, context);
exit;
end;
if tmp.Name.ToLower = 'tdate' then
begin
Result := True;
output := SerTDate(data, dataType, context);
exit;
end;
if tmp.Name.ToLower = 'ttime' then
begin
Result := True;
output := SerTTime(data, dataType, context);
exit;
end;
if tmp.Name.ToLower = 'tjsonvalue' then
begin
Result := True;
output := SerTJSONValue(data, dataType, context);
exit;
end;
if context.settings.TreatStringDictionaryAsObject and
(tmp.Name.ToLower.StartsWith('tdictionary<system.string,', True) or
tmp.Name.ToLower.StartsWith('tdictionary<string,', True)) then
begin
Result := True;
output := SerTDictionaryStringKey(data.AsObject, dataType, context);
exit;
end;
if tmp.Name.ToLower.StartsWith('tpair<', True) then
begin
Result := True;
output := SerTPair(data, dataType, context);
exit;
end;
if tmp.Name.ToLower.StartsWith('tenumerable<', True) then
begin
Result := True;
output := SerTEnumerable(data.AsObject, dataType, context);
exit;
end;
tmp := tmp.BaseType;
end;
Result := False;
end;
function SerObject(value: TValue; context: TSerContext; isRecord: Boolean)
: TJSONValue;
var
// data: TObject;
dataType: TRttiType;
attribute: TCustomAttribute;
found: Boolean;
resultObject: TJSONObject;
objectFields: TArray<TRttiField>;
field: TRttiField;
jsonFieldName: string;
fieldValue: TValue;
serializedField: TJSONValue;
nillable: Boolean;
converter: IDJConverterInterface;
nullIfEmptyString: Boolean;
begin
dataType := context.RTTI.GetType(value.TypeInfo);
// TODO: split this function in smaller parts
// handle a "standard" object and serialize it
if context.settings.RequireSerializableAttributeForNonRTLClasses then
begin
// Ensure the object has the serializable attribute. (Fields added later)
found := False;
for attribute in dataType.GetAttributes() do
begin
if attribute is DJSerializableAttribute then
begin
found := True;
break;
end;
end;
if not found then
begin
raise EDJError.Create
('Given object type is missing the JSONSerializable attribute. ',
context);
end;
end;
// Init the result object
resultObject := TJSONObject.Create;
context.AddHeapObject(resultObject);
Result := resultObject;
// adding fields to the object
objectFields := dataType.GetFields;
for field in objectFields do
begin
// default values for properties
found := False;
nillable := True;
converter := nil;
nullIfEmptyString := false;
// check for the attributes
for attribute in field.GetAttributes() do
begin
if attribute is DJValueAttribute then
begin
// found the value attribute (this needs to be serialized)
found := True;
jsonFieldName := (attribute as DJValueAttribute).Name.Trim;
end
else if attribute is DJNonNilableAttribute then
begin
// nil is not allowed
nillable := False;
end
else if attribute is IDJConverterInterface then
begin
converter := attribute as IDJConverterInterface;
end
else if attribute is DJNullIfEmptyStringAttribute then
begin
nullIfEmptyString := True;
end;
end;
// check if nillable is allowed
if context.settings.IgnoreNonNillable then
begin
nillable := True;
end;
if not found then
begin
// skip this field since it is not opted-in for serialization
continue;
end;
// check if the field name is valid
if string.IsNullOrWhiteSpace(jsonFieldName) then
begin
raise EDJError.Create
('Invalid JSON field name: is null or whitespace. ', context);
end;
if isRecord then
begin
fieldValue := field.GetValue(value.GetReferenceToRawData);
end
else
begin
fieldValue := field.GetValue(value.AsObject);
end;
context.PushPath(jsonFieldName);
// check if field is nil
if fieldValue.IsObject then
begin
if (not nillable) and (fieldValue.AsObject = nil) then
begin
raise EDJNilError.Create
('Field value must not be nil, but was nil. ', context);
end;
end;
// serialize
if converter <> nil then
begin
// use the converter
serializedField := converter.ToJSONinternal(fieldValue);
end
else
begin
if fieldValue.IsObject and (fieldValue.AsObject = nil) then
begin
// field is nil and allowed to be nil, hence return a json null
serializedField := TJSONNull.Create;
end
else
begin
// use the default serialization
serializedField := SerializeInternal(fieldValue, context, nullIfEmptyString);
end;
end;
context.PopPath;
// add the variable to the resulting object
context.RemoveHeapObject(serializedField);
resultObject.AddPair(jsonFieldName, serializedField);
end;
end;
function SerializeInternal(value: TValue; context: TSerContext; nullIfEmptyString: Boolean = false): TJSONValue;
var
dataType: TRttiType;
begin
// check for the type and call the appropriate subroutine for serialization
dataType := context.RTTI.GetType(value.TypeInfo);
// check if it a object and
if value.IsObject then
begin
// check if the object was already / is in the process of being serialized
if context.IsTracked(value.AsObject) then
begin
raise EDJCycleError.Create
('A cycle was detected during serialization!', context);
end;
context.Track(value.AsObject);
end;
// checking if a special case handled the type of data
if SerHandledSpecialCase(value, dataType, Result, context) then
begin
exit;
end;
// handle other cases
if value.IsArray then
begin
Result := SerArray(value, context);
end
else if value.Kind = TTypeKind.tkFloat then
begin
Result := SerFloat(value, context);
end
else if value.Kind = TTypeKind.tkInt64 then
begin
Result := SerInt64(value, context);
end
else if value.Kind = TTypeKind.tkInteger then
begin
Result := SerInt(value, context);
end
else if value.IsType<string>(False) then
begin
Result := SerString(value, context, nullIfEmptyString);
end
else if value.IsEmpty then
begin
Result := TJSONNull.Create;
context.AddHeapObject(Result);
end
else if value.IsType<Boolean> then
begin
Result := TJSONBool.Create(value.AsBoolean);
context.AddHeapObject(Result);
end
else if value.IsObject then
begin
Result := SerObject(value, context, False);
end
else if value.Kind = TTypeKind.tkRecord then
begin
Result := SerObject(value, context, True);
end
else
begin
raise EDJError.Create('Type not supported for serialization. ', context);
end;
end;
function DerSpecialConstructors(dataType: TRttiType; method: TRttiMethod;
var params: TArray<TValue>): Boolean;