-
Notifications
You must be signed in to change notification settings - Fork 55
/
json-convert.ts
1397 lines (1174 loc) · 53.8 KB
/
json-convert.ts
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
import { Any } from "./any";
import { OperationMode, PropertyConvertingMode, PropertyMatchingRule, ValueCheckingMode } from "./json-convert-enums";
import { MappingOptions, Settings } from "./json-convert-options";
/**
* Offers a simple API for mapping JSON objects to TypeScript/JavaScript classes and vice versa.
*
* @see https://www.npmjs.com/package/json2typescript full documentation on NPM
*/
export class JsonConvert {
////////////////
// PROPERTIES //
////////////////
/**
* Determines how the JsonConvert class instance should operate.
*
* You may assign three different values:
* - OperationMode.DISABLE: json2typescript will be disabled, no type checking or mapping is done
* - OperationMode.ENABLE: json2typescript is enabled, but only errors are logged
* - OperationMode.LOGGING: json2typescript is enabled and detailed information is logged
*/
private _operationMode: number = OperationMode.ENABLE;
/**
* Determines how the JsonConvert class instance should operate.
*
* You may assign three different values:
* - OperationMode.DISABLE: json2typescript will be disabled, no type checking or mapping is done
* - OperationMode.ENABLE: json2typescript is enabled, but only errors are logged
* - OperationMode.LOGGING: json2typescript is enabled and detailed information is logged
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get operationMode(): number {
return this._operationMode;
}
/**
* Determines how the JsonConvert class instance should operate.
*
* You may assign three different values:
* - OperationMode.DISABLE: json2typescript will be disabled, no type checking or mapping is done
* - OperationMode.ENABLE: json2typescript is enabled, but only errors are logged
* - OperationMode.LOGGING: json2typescript is enabled and detailed information is logged
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set operationMode(value: number) {
if (value in OperationMode) this._operationMode = value;
}
/**
* Determines which types are allowed to be null.
* This setting may be overridden by property settings (see PropertyConvertingMode).
*
* You may assign three different values:
* - ValueCheckingMode.ALLOW_NULL: all given values are allowed to be null
* - ValueCheckingMode.ALLOW_OBJECT_NULL: objects are allowed to be null, primitive types are not allowed to be null
* - ValueCheckingMode.DISALLOW_NULL: no null values are tolerated
*/
private _valueCheckingMode: number = ValueCheckingMode.ALLOW_OBJECT_NULL;
/**
* Determines which types are allowed to be null.
* This setting may be overridden by property settings (see PropertyConvertingMode).
*
* You may assign three different values:
* - ValueCheckingMode.ALLOW_NULL: all given values are allowed to be null
* - ValueCheckingMode.ALLOW_OBJECT_NULL: objects are allowed to be null, primitive types are not allowed to be null
* - ValueCheckingMode.DISALLOW_NULL: no null values are tolerated
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get valueCheckingMode(): number {
return this._valueCheckingMode;
}
/**
* Determines which types are allowed to be null.
* This setting may be overridden by property settings (see PropertyConvertingMode).
*
* You may assign three different values:
* - ValueCheckingMode.ALLOW_NULL: all given values are allowed to be null
* - ValueCheckingMode.ALLOW_OBJECT_NULL: objects are allowed to be null, primitive types are not allowed to be null
* - ValueCheckingMode.DISALLOW_NULL: no null values are tolerated
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set valueCheckingMode(value: number) {
if (value in ValueCheckingMode) this._valueCheckingMode = value;
}
/**
* Determines whether a missing or undefined property value should be considered as null or not.
*
* If true, a missing JSON value will be added and set as null before deserialization.
* For serialization, undefined values will be set to null before serialization.
*
* The ValueCheckingMode and PropertyConvertingMode determine whether an error will be thrown during
* serialization or deserialization.
*/
private _mapUndefinedToNull: boolean = false;
/**
* Determines whether a missing or undefined property value should be considered as null or not.
*
* If true, a missing JSON value will be added and set as null before deserialization.
* For serialization, undefined values will be set to null before serialization.
*
* ValueCheckingMode and PropertyConvertingMode determine whether an error will be thrown during
* serialization or deserialization.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get mapUndefinedToNull(): boolean {
return this._mapUndefinedToNull;
}
/**
* Determines whether a missing or undefined property value should be considered as null or not.
*
* If true, a missing JSON value will be added and set as null before deserialization.
* For serialization, undefined values will be set to null before serialization.
*
* The ValueCheckingMode and PropertyConvertingMode determine whether an error will be thrown during
* serialization or deserialization.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set mapUndefinedToNull(value: boolean) {
this._mapUndefinedToNull = value;
}
/**
* Determines whether primitive types should be checked.
* If true, it will be allowed to assign primitive to other primitive types.
*/
private _ignorePrimitiveChecks: boolean = false;
/**
* Determines whether primitive types should be checked.
* If true, it will be allowed to assign primitive to other primitive types.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get ignorePrimitiveChecks(): boolean {
return this._ignorePrimitiveChecks;
}
/**
* Determines whether primitive types should be checked.
* If true, it will be allowed to assign primitive to other primitive types.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set ignorePrimitiveChecks(value: boolean) {
this._ignorePrimitiveChecks = value;
}
/**
* Determines the rule of how JSON properties shall be matched with class properties during deserialization.
*
* You may assign the following values:
* - PropertyMatchingRule.CASE_STRICT: JSON properties need to match exactly the names in the decorators
* - PropertyMatchingRule.CASE_INSENSITIVE: JSON properties need to match names in the decorators, but names they
* are not case sensitive
*/
private _propertyMatchingRule: number = PropertyMatchingRule.CASE_STRICT;
/**
* Determines the rule of how JSON properties shall be matched with class properties during deserialization.
*
* You may assign the following values:
* - PropertyMatchingRule.CASE_STRICT: JSON properties need to match exactly the names in the decorators
* - PropertyMatchingRule.CASE_INSENSITIVE: JSON properties need to match names in the decorators, but names they
* are not case sensitive
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get propertyMatchingRule(): number {
return this._propertyMatchingRule;
}
/**
* Determines the rule of how JSON properties shall be matched with class properties during deserialization.
*
* You may assign the following values:
* - PropertyMatchingRule.CASE_STRICT: JSON properties need to match exactly the names in the decorators
* - PropertyMatchingRule.CASE_INSENSITIVE: JSON properties need to match names in the decorators, but names they
* are not case sensitive
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set propertyMatchingRule(value: number) {
if (value in PropertyMatchingRule) this._propertyMatchingRule = value;
}
/**
* Determines how nullable property types should be serialized and deserialized.
* Nullable types are either missing (in JSON), undefined (in TypeScript) or null (both).
*
* If the propertyConvertingMode has a non-undefined value, it overrides the individual settings of every property.
*
* The values should be used as follows:
* Determines how nullable property types should be serialized and deserialized.
* Nullable types are either missing (in JSON), undefined (in TypeScript) or null (both).
*
* If the propertyConvertingMode has a non-undefined value, it overrides the individual settings of every property.
*
* The values should be used as follows:
* - MAP_NULLABLE: the mapper is applied, type is checked
* - IGNORE_NULLABLE: the mapper is not applied if the property is missing, undefined or null; the property is
* not added to the result
* - PASS_NULLABLE: the mapper is not applied if the property is missing, undefined or null; the property is
* added with its value to the result
*/
private _propertyConvertingMode: PropertyConvertingMode | undefined = undefined;
/**
* Determines how nullable property types should be serialized and deserialized.
* Nullable types are either missing (in JSON), undefined (in TypeScript) or null (both).
*
* If the propertyConvertingMode has a non-undefined value, it overrides the individual settings of every property.
*
* The values should be used as follows:
* - MAP_NULLABLE: the mapper is applied, type is checked
* - IGNORE_NULLABLE: the mapper is not applied if the property is missing, undefined or null; the property is
* not added to the result
* - PASS_NULLABLE: the mapper is not applied if the property is missing, undefined or null; the property is
* added with its value to the result
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get propertyConvertingMode(): PropertyConvertingMode | undefined {
return this._propertyConvertingMode;
}
/**
* Determines how nullable property types should be serialized and deserialized.
* Nullable types are either missing (in JSON), undefined (in TypeScript) or null (both).
*
* If the propertyConvertingMode has a non-undefined value, it overrides the individual settings of every property.
*
* The values should be used as follows:
* - MAP_NULLABLE: the mapper is applied, type is checked
* - IGNORE_NULLABLE: the mapper is not applied if the property is missing, undefined or null; the property is
* not added to the result
* - PASS_NULLABLE: the mapper is not applied if the property is missing, undefined or null; the property is
* added with its value to the result
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set propertyConvertingMode(value: PropertyConvertingMode | undefined) {
this._propertyConvertingMode = value;
}
/**
* @deprecated
*/
get ignoreRequiredCheck(): boolean {
return this.propertyConvertingMode === PropertyConvertingMode.IGNORE_NULLABLE;
}
/**
* @deprecated
*/
set ignoreRequiredCheck(value: boolean) {
this.propertyConvertingMode = value ? PropertyConvertingMode.IGNORE_NULLABLE : undefined;
}
/**
* Determines if discriminators should be used.
* If this option is set to true, all registered classes will be serialized with an additional discriminator
* property (default: "$type"), which has the key of the class (given in the @JsonObject decorator) as value.
* When deserializing an object containing the discriminator property, json2typescript will attempt to
* automatically instantiate the correct type (by comparing the value of the discriminator property with the
* registered classes).
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
private _useDiscriminator: boolean = false;
/**
* Determines if discriminators should be used.
* If this option is set to true, all registered classes will be serialized with an additional discriminator
* property (default: "$type"), which has the key of the class (given in the @JsonObject decorator) as value.
* When deserializing an object containing the discriminator property, json2typescript will attempt to
* automatically instantiate the correct type (by comparing the value of the discriminator property with the
* registered classes).
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get useDiscriminator(): boolean {
return this._useDiscriminator;
}
/**
* Determines if discriminators should be used.
* If this option is set to true, all registered classes will be serialized with an additional discriminator
* property (default: "$type"), which has the key of the class (given in the @JsonObject decorator) as value.
* When deserializing an object containing the discriminator property, json2typescript will attempt to
* automatically instantiate the correct type (by comparing the value of the discriminator property with the
* registered classes).
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set useDiscriminator(value: boolean) {
this._useDiscriminator = value;
}
/**
* Defines the name of the discriminator property.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
private _discriminatorPropertyName: string = "$type";
/**
* Defines the name of the discriminator property.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get discriminatorPropertyName(): string {
return this._discriminatorPropertyName;
}
/**
* Defines the name of the discriminator property.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set discriminatorPropertyName(value: string) {
this._discriminatorPropertyName = value;
}
/**
* Determines all classes which should use the lazy-loading or discriminator feature.
* Only classes provided here can be used with lazy-loading or the discriminator property.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
private _classes: Map<string, (new() => any)> = new Map();
/**
* Determines all classes which should use the lazy-loading or discriminator feature.
* Only classes provided here can be used with lazy-loading or the discriminator property.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
private get classes(): Map<string, (new() => any)> {
return this._classes;
}
/////////////////
// CONSTRUCTOR //
/////////////////
/**
* Constructor.
*
* To learn more about the params, check the documentation of the equally named class properties.
*
* @param operationMode optional param (default: OperationMode.ENABLE)
* @param valueCheckingMode optional param (default: ValueCheckingMode.ALLOW_OBJECT_NULL)
* @param ignorePrimitiveChecks optional param (default: false)
* @param propertyMatchingRule optional param (default: PropertyMatchingRule.CASE_STRICT)
*/
constructor(operationMode?: number, valueCheckingMode?: number, ignorePrimitiveChecks?: boolean, propertyMatchingRule?: number) {
if (operationMode !== undefined && operationMode in OperationMode) this.operationMode = operationMode;
if (valueCheckingMode !== undefined && valueCheckingMode in ValueCheckingMode) this.valueCheckingMode = valueCheckingMode;
if (ignorePrimitiveChecks !== undefined) this.ignorePrimitiveChecks = ignorePrimitiveChecks;
if (propertyMatchingRule !== undefined) this.propertyMatchingRule = propertyMatchingRule;
}
////////////////////
// PUBLIC METHODS //
////////////////////
/**
* Registers a list of classes to be used in the discriminator feature.
* After registering these classes, they may be used for the discriminator feature.
*
* @param classReferences the class references
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
registerClasses(...classReferences: { new(): any }[]): void {
classReferences.forEach((classReference: { new(): any }) => {
const key = classReference.prototype[Settings.CLASS_IDENTIFIER] || classReference.name;
if (key) {
this.classes.set(key, classReference);
}
});
}
/**
* Unregisters a list of classes from the discriminator feature.
* After unregistering these classes, they cannot be used anymore for the discriminator feature.
*
* @param classReferences the class references
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
unregisterClasses(...classReferences: { new(): any }[]): void {
classReferences.forEach((classReference: { new(): any }) => {
const key = classReference.prototype[Settings.CLASS_IDENTIFIER] || classReference.name;
this.classes.delete(key);
});
}
/**
* Unregisters all classes from discriminator feature.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
unregisterAllClasses(): void {
this.classes.clear();
}
/**
* Tries to serialize a TypeScript object or array of objects to JSON using the mappings defined on
* the specified class reference. Note that if a class reference is provided, it will be used as
* the source of property mapping for serialization, even if the object or one of its elements is
* an instance of a different class with its own mappings. Also, ONLY the properties from the
* class reference will be serialized - any additional properties on the object(s) will be silently
* ignored.
*
* @param data object or array of objects
* @param classReference the class reference which provides the property mappings to use
*
* @returns the JSON object
*
* @throws an Error in case of failure
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
serialize<T extends object, U extends object = {}>(data: T | T[], classReference?: { new(): U }): any | any[] {
if (this.operationMode === OperationMode.DISABLE) {
return data;
}
// Call the appropriate method depending on the type
if (data instanceof Array) {
return this.serializeArray(data, classReference);
} else if (typeof data === "object") { // careful: an array is an object in TypeScript!
return this.serializeObject(data, classReference);
} else {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter data in JsonConvert.serialize() is not in valid format (object or array)." +
"\n"
);
}
}
/**
* Tries to serialize a TypeScript object to a JSON object using either the mappings on the
* provided class reference, if present, or on the provided object. Note that if a class
* reference is provided, it will be used as the source of property mapping for serialization,
* even if the object is itself an instance of a different class with its own mappings.
* Also, ONLY the properties from the class reference will be serialized - any additional
* properties on the object will be silently ignored.
*
* @param data object containing the values to be mapped to a JSON object, must be an
* instance of a class with JSON mappings if no class reference is provided
* @param classReference optional class reference which provides the property mappings to use
*
* @returns the JSON object
*
* @throws an Error in case of failure
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
serializeObject<T extends object, U extends object = {}>(data: T, classReference?: { new(): U }): any {
if (this.operationMode === OperationMode.DISABLE) {
return data;
}
data = this.mapUndefinedToNull && data === undefined ? null as any : data;
// Check if the passed type is allowed
if (data === undefined) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter instance in JsonConvert.serializeObject() is undefined. This is not a valid JSON format." +
"\n"
);
} else if (data === null) {
if (this.valueCheckingMode === ValueCheckingMode.DISALLOW_NULL) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter instance in JsonConvert.serializeObject() is null. You have specified to " +
"disallow null values." +
"\n"
);
} else {
return data;
}
} else if (typeof (data) !== "object" || data instanceof Array) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter instance in JsonConvert.serializeObject() is not of type object." +
"\n"
);
}
// Now serialize and return the plain object
if (this.operationMode === OperationMode.LOGGING) {
console.log("----------");
console.log("Receiving JavaScript instance:");
console.log(data);
}
let jsonObject: any = {};
let instance: T | U;
if (!!classReference) {
instance = new classReference();
} else {
instance = data;
}
// Loop through all initialized class properties on the mapping instance
for (const propertyKey of Object.keys(instance)) {
try {
this.serializeObject_loopProperty(data, instance, propertyKey, jsonObject);
} catch (ex) {
if (this.operationMode === OperationMode.LOGGING) {
console.log("Failed to serialize property:");
console.log(ex);
console.log("----------");
}
throw ex;
}
}
if (this.operationMode === OperationMode.LOGGING) {
console.log("Returning JSON object:");
console.log(jsonObject);
console.log("----------");
}
return jsonObject;
}
/**
* Tries to serialize a TypeScript array to a JSON array using either the mappings on the
* provided class reference, if present, or on the provided object. Note that if a class
* reference is provided, ALL objects in the array will be serialized using the mappings
* from that class reference, even if they're actually instances of a different class.
* Also, ONLY the properties from the class reference will be serialized - any additional
* properties on the objects will be silently ignored.
*
* @param dataArray array of objects containing the values to be mapped to a JSON object, which
* must be instances of classes with JSON mappings if no class reference is provided
* @param classReference optional class reference which provides the property mappings to use
*
* @returns the JSON array
*
* @throws an Error in case of failure
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
serializeArray<T extends object, U extends object = {}>(dataArray: T[], classReference?: { new(): U }): any[] {
if (this.operationMode === OperationMode.DISABLE) {
return dataArray;
}
dataArray = this.mapUndefinedToNull && dataArray === undefined ? null as any : dataArray;
// Check if the passed type is allowed
if (dataArray === undefined) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter instanceArray in JsonConvert.serializeArray() is undefined. This is not a valid JSON format." +
"\n"
);
} else if (dataArray === null) {
if (this.valueCheckingMode === ValueCheckingMode.DISALLOW_NULL) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter instanceArray in JsonConvert.serializeArray() is null. You have specified to " +
"disallow null values." +
"\n"
);
} else {
return dataArray;
}
} else if (typeof (dataArray) !== "object" || dataArray instanceof Array === false) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter instanceArray in JsonConvert.serializeArray() is not of type array." +
"\n"
);
}
// Now serialize and return the plain object
if (this.operationMode === OperationMode.LOGGING) {
console.log("----------");
console.log("Receiving JavaScript array:");
console.log(dataArray);
}
let jsonArray: object[] = [];
// Loop through all array elements
for (const dataObject of dataArray) {
jsonArray.push(this.serializeObject(dataObject, classReference));
}
if (this.operationMode === OperationMode.LOGGING) {
console.log("Returning JSON array:");
console.log(jsonArray);
console.log("----------");
}
return jsonArray;
}
/**
* Tries to deserialize given JSON to a TypeScript object or array of objects.
*
* @param json the JSON as object or array
* @param classReference the class reference
*
* @returns the deserialized data (TypeScript instance or array of TypeScript instances)
*
* @throws an Error in case of failure
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
deserialize<T extends object>(json: object | object[], classReference: { new(): T } | null = null): T | T[] {
if (this.operationMode === OperationMode.DISABLE) {
return json as T | T[];
}
// Call the appropriate method depending on the type
if (json instanceof Array) {
return this.deserializeArray(json, classReference);
} else if (typeof json === "object") { // careful: an array is an object in TypeScript!
return this.deserializeObject(json, classReference);
} else {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter json in JsonConvert.deserialize() is not in valid JSON format (object or array)." +
"\n"
);
}
}
/**
* Tries to deserialize a JSON object to a TypeScript object.
*
* @param jsonObject the JSON object
* @param classReference the class reference
*
* @returns the deserialized TypeScript instance
*
* @throws an Error in case of failure
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
deserializeObject<T extends object>(jsonObject: any, classReference: { new(): T } | null = null): T {
if (this.operationMode === OperationMode.DISABLE) {
return jsonObject as T;
}
const realClassReference = this.getRealClassReference(jsonObject, classReference);
jsonObject = this.mapUndefinedToNull && jsonObject === undefined ? null as any : jsonObject;
// Check if the passed type is allowed
if (jsonObject === undefined) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter jsonObject in JsonConvert.deserializeObject() is undefined. This is not a valid JSON format." +
"\n"
);
} else if (jsonObject === null) {
if (this.valueCheckingMode === ValueCheckingMode.DISALLOW_NULL) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter jsonObject in JsonConvert.deserializeObject() is null. You have specified to " +
"disallow null values." +
"\n"
);
} else {
return jsonObject as T;
}
} else if (typeof (jsonObject) !== "object" || jsonObject instanceof Array) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter jsonObject in JsonConvert.deserializeObject() is not of type object." +
"\n"
);
}
// Now deserialize and return the instance
if (this.operationMode === OperationMode.LOGGING) {
console.log("----------");
console.log("Receiving JSON object:");
console.log(jsonObject);
}
let instance: T = new realClassReference();
// Loop through all initialized class properties
for (const propertyKey of Object.keys(instance)) {
try {
this.deserializeObject_loopProperty(instance, propertyKey, jsonObject);
} catch (ex) {
if (this.operationMode === OperationMode.LOGGING) {
console.log("Failed to deserialize property:");
console.log(ex);
console.log("----------");
}
throw ex;
}
}
if (this.operationMode === OperationMode.LOGGING) {
console.log("Returning CLASS instance:");
console.log(instance);
console.log("----------");
}
return instance;
}
/**
* Tries to deserialize a JSON array to a TypeScript array.
*
* @param jsonArray the JSON array
* @param classReference the object class
*
* @returns the deserialized array of TypeScript instances
*
* @throws an Error in case of failure
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
deserializeArray<T extends object>(jsonArray: any[], classReference: { new(): T } | null = null): T[] {
if (this.operationMode === OperationMode.DISABLE) {
return jsonArray as T[];
}
jsonArray = this.mapUndefinedToNull && jsonArray === undefined ? null as any : jsonArray;
// Check if the passed type is allowed
if (jsonArray === undefined) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter jsonArray in JsonConvert.deserializeObject() is undefined. This is not a valid JSON format." +
"\n"
);
} else if (jsonArray === null) {
if (this.valueCheckingMode === ValueCheckingMode.DISALLOW_NULL) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter jsonArray in JsonConvert.deserializeObject() is null. You have specified to " +
"disallow null values." +
"\n"
);
} else {
return jsonArray as T[];
}
} else if (typeof (jsonArray) !== "object" || jsonArray instanceof Array === false) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter jsonArray in JsonConvert.deserializeArray() is not of type array." +
"\n"
);
}
// Now deserialize and return the array
if (this.operationMode === OperationMode.LOGGING) {
console.log("----------");
console.log("Receiving JSON array:");
console.log(jsonArray);
}
let array: T[] = [];
// Loop through all array elements
for (const jsonObject of jsonArray) {
array.push(this.deserializeObject<T>(jsonObject, classReference));
}
if (this.operationMode === OperationMode.LOGGING) {
console.log("Returning array of CLASS instances:");
console.log(array);
console.log("----------");
}
return array;
}
/////////////////////
// PRIVATE METHODS //
/////////////////////
/**
* Returns the correct class reference for the provided JSON object.
* If the provided class reference is null, the class reference is retrieved from the class map using the discriminator property.
*
* @param jsonObject the JSON object
* @param classReference the class reference
* @throws throws an Error in case of failure
*/
private getRealClassReference<T extends object>(jsonObject: any, classReference: { new(): T } | null): { new(): T } {
// First determine if the discriminator is used or not
if (this.useDiscriminator) {
// Check if we find the $type property. If not, throw an error.
if (jsonObject.hasOwnProperty(this.discriminatorPropertyName)) {
const discriminatorValue: string = jsonObject[this.discriminatorPropertyName] ?? "";
const classReferenceNameFromMap = this.classes.get(discriminatorValue);
if (classReferenceNameFromMap !== undefined && classReferenceNameFromMap !== null) {
return classReferenceNameFromMap;
} else {
throw new Error(
"Fatal error in JsonConvert. " +
"Discriminator value \"" + discriminatorValue + "\" could not be found in the registered classes. " +
"Make sure you register the class using the method JsonConvert.registerClasses(" + discriminatorValue + ")" +
"\n"
);
}
} else {
throw new Error(
"Fatal error in JsonConvert. " +
"Discriminator property \"" + this.discriminatorPropertyName + "\" is missing in JSON object." +
"\n"
);
}
} else {
// Make sure the class reference is given for if the discriminator is disabled
if (classReference === null) {
throw new Error(
"Fatal error in JsonConvert. " +
"Passed parameter classReference in JsonConvert.deserialize() is null. " +
"This is only allowed if discriminator feature is enabled." +
"\n"
);
}
return classReference;
}
}
/**
* Tries to find the JSON mapping for a given class property from the given instance used for mapping,
* and finally assign the value from the given dataObject
*
* @param dataObject the object containing the value to be assigned
* @param instance the instance of the class used for mapping
* @param classPropertyName the property name
* @param json the JSON object
* @throws throws an Error in case of failure
*/
private serializeObject_loopProperty(dataObject: any, instance: any, classPropertyName: string, json: any): void {
// Check if a JSON-object mapping is possible for a property
const mappingOptions: MappingOptions | null = this.getClassPropertyMappingOptions(instance, classPropertyName);
if (mappingOptions === null) {
return;
}
// Get expected and real values
const jsonPropertyName: string = mappingOptions.jsonPropertyName;
const expectedJsonType: any = mappingOptions.expectedJsonType;
const convertingMode: PropertyConvertingMode = this.propertyConvertingMode ?? mappingOptions.convertingMode;
const customConverter: any = mappingOptions.customConverter;
let classInstancePropertyValue: any = dataObject[classPropertyName];
// Check if we have a nullable type
classInstancePropertyValue = this.mapUndefinedToNull && classInstancePropertyValue === undefined ? null : classInstancePropertyValue;
if (classInstancePropertyValue === undefined || classInstancePropertyValue === null) {
if (convertingMode === PropertyConvertingMode.IGNORE_NULLABLE) {
return;
}
if (convertingMode === PropertyConvertingMode.PASS_NULLABLE) {
json[jsonPropertyName] = classInstancePropertyValue;
return;
}
}
// Map the property
try {
json[jsonPropertyName] = customConverter !== null ?
customConverter.serialize(classInstancePropertyValue) :
this.convertProperty(expectedJsonType, classInstancePropertyValue, convertingMode, true);
const classConstructorName = dataObject?.constructor?.name;
if (this._useDiscriminator && json instanceof Object) {
this.classes.forEach((classDataObject: {new(): any}, key: string) => {
if (classDataObject.name === classConstructorName) {
json[this._discriminatorPropertyName] = key;
}
});
}
} catch (e) {
throw new Error(
"Fatal error in JsonConvert. " +
"Failed to map the JavaScript instance of class \"" + instance[Settings.CLASS_IDENTIFIER] + "\" to JSON because of a type error.\n\n" +
"\tClass property: \n\t\t" + classPropertyName + "\n\n" +
"\tClass property value: \n\t\t" + classInstancePropertyValue + "\n\n" +
"\tExpected type: \n\t\t" + this.getExpectedType(expectedJsonType) + "\n\n" +
"\tRuntime type: \n\t\t" + this.getTrueType(classInstancePropertyValue) + "\n\n" +
"\tJSON property: \n\t\t" + jsonPropertyName + "\n\n" +
e.message + "\n"
);
}
}
/**
* Tries to find the JSON mapping for a given class property and finally assign the value.
*
* @param instance the instance of the class
* @param classPropertyName the property name
* @param json the JSON object
*
* @throws throws an Error in case of failure
*/
private deserializeObject_loopProperty(instance: any, classPropertyName: string, json: any): void {
const mappingOptions: MappingOptions | null = this.getClassPropertyMappingOptions(instance, classPropertyName);
if (mappingOptions === null) {
return;
}
// Get expected and real values
const jsonPropertyName: string = mappingOptions.jsonPropertyName;
let expectedJsonType: any = mappingOptions.expectedJsonType;
const convertingMode: PropertyConvertingMode = this.propertyConvertingMode ?? mappingOptions.convertingMode;
const customConverter: any = mappingOptions.customConverter;
let jsonValue: any = undefined;
try {
jsonValue = this.getObjectValue(json, jsonPropertyName);
} catch {}
// Check if we have a nullable type
jsonValue = this.mapUndefinedToNull && jsonValue === undefined ? null : jsonValue;
if (jsonValue === undefined || jsonValue === null) {