Debian Codegraph @

src/compatibility/delphi-only/fcl-json/fpjsonrtti.pas

raw
1 unit fpjsonrtti;
2
3 {$I castleconf.inc} // avoid useless Delphi warnings
4 {$warn USE_BEFORE_DEF off}
5
6 /// {$mode objfpc}
7
8 interface
9
10 uses
11 Classes, SysUtils, contnrs, typinfo, fpjson, rttiutils, jsonparser;
12
13 Const
14 RFC3339DateTimeFormat = 'yyyy"-"mm"-"dd"T"hh":"nn":"ss';
15 RFC3339DateTimeFormatMsec = RFC3339DateTimeFormat+'.zzz';
16
17
18 Type
19
20 TJSONStreamEvent = Procedure (Sender : TObject; AObject : TObject; JSON : TJSONObject) of object;
21 TJSONPropertyEvent = Procedure (Sender : TObject; AObject : TObject; Info : PPropInfo; var Res : TJSONData) of object;
22
23 TJSONStreamOption = (jsoStreamChildren, // If set, children will be streamed in 'Children' Property
24 jsoEnumeratedAsInteger, // Write enumerated as integer. Default is string.
25 jsoSetAsString, // Write Set as a string. Default is an array.
26 jsoSetEnumeratedAsInteger, // Write enumerateds in set array as integers.
27 jsoSetBrackets, // Use brackets when creating set as array
28 jsoComponentsInline, // Always stream components inline. Default is to stream name, unless csSubcomponent in ComponentStyle
29 jsoTStringsAsArray, // Stream TStrings as an array of strings. Associated objects are not streamed.
30 jsoTStringsAsObject, // Stream TStrings as an object : string = { object }
31 jsoDateTimeAsString, // Format a TDateTime value as a string
32 jsoUseFormatString, // Use FormatString when creating JSON strings.
33 jsoCheckEmptyDateTime, // If TDateTime value is empty and jsoDateTimeAsString is used, 0 date returns empty string
34 jsoLegacyDateTime, // Set this to enable old date/time formatting. Current behaviour is to save date/time as a ISO 9601 value.
35 jsoLowerPropertyNames, // Set this to force lowercase names when streaming to JSON.
36 jsoStreamTList // Set this to assume that TList contains a list of TObjects. Use with care!
37 );
38 TJSONStreamOptions = Set of TJSONStreamOption;
39
40 TJSONFiler = Class(TComponent)
41 Protected
42 Procedure Error(Const Msg : String); overload;
43 Procedure Error(Const FMT : String; Args : Array of const); overload;
44 end;
45
46 { TJSONStreamer }
47
48 TJSONStreamer = Class(TJSONFiler)
49 private
50 FAfterStreamObject: TJSONStreamEvent;
51 FBeforeStreamObject: TJSONStreamEvent;
52 FChildProperty: String;
53 FDateTimeFormat: String;
54 FOnStreamProperty: TJSONPropertyEvent;
55 FOptions: TJSONStreamOptions;
56 function GetChildProperty: String;
57 function IsChildStored: boolean;
58 function StreamChildren(AComp: TComponent): TJSONArray;
59 protected
60 function StreamClassProperty(Const AObject: TObject): TJSONData; virtual;
61 Function StreamProperty(Const AObject : TObject; Const PropertyName : String) : TJSONData; overload;
62 Function StreamProperty(Const AObject : TObject; PropertyInfo : PPropInfo) : TJSONData; overload;
63 Function FormatDateProp(const DateTime : TDateTime) : TJSONString;
64 Public
65 Constructor Create(AOwner : TComponent); override;
66 Destructor Destroy;override;
67 //
68 // Basic functions
69 //
70 // Use RTTI to stream object.
71 // If AObject is of type TStrings or TCollection, special treatment occurs:
72 // TStrings results in { Strings: [S,S,S] } or { Strings: { "S1" : O1, "S2" : O2 }} depending on Options.
73 // Collection results in { Items: [I,I,I] }
74 Function ObjectToJSON(Const AObject : TObject) : TJSONObject;
75 // Stream a collection - always returns an array
76 function StreamCollection(Const ACollection: TCollection): TJSONArray;
77 // Stream an objectlist - always returns an array
78 function StreamObjectList(Const AnObjectList: TObjectList): TJSONArray;
79 // Stream a List - always returns an array
80 function StreamTList(Const AList: TList): TJSONArray;
81 // Stream a TStrings instance as an array
82 function StreamTStringsArray(Const AStrings: TStrings): TJSONArray;
83 // Stream a TStrings instance as an object
84 function StreamTStringsObject(Const AStrings: TStrings): TJSONObject;
85 // Stream a TStrings instance. Takes into account Options.
86 function StreamTStrings(Const AStrings: TStrings): TJSONData;
87 // Stream a variant as JSON.
88 function StreamVariant(const Data: Variant): TJSONData; virtual;
89 //
90 // Some utility functions.
91 //
92 // Call ObjectToJSON and convert result to JSON String.
93 Function ObjectToJSONString(AObject : TObject) : TJSONStringType;
94 // Convert TSTrings to JSON string with array or Object.
95 Function StringsToJSON(Const Strings : TStrings; AsObject : Boolean = False) : TJSONStringType;
96 // Convert collection to JSON string
97 Function CollectionToJSON(Const ACollection : TCollection) : TJSONStringType;
98 // Convert variant to JSON String
99 Function VariantToJSON(Const Data : Variant) : TJSONStringType;
100 Published
101 // Format used when formatting DateTime values. Only used in conjunction with jsoDateTimeToString
102 Property DateTimeFormat : String Read FDateTimeFormat Write FDateTimeFormat;
103 // Options to use when streaming
104 Property Options : TJSONStreamOptions Read FOptions Write FOptions;
105 // Called before streaming an object with ObjectToJSON
106 Property BeforeStreamObject : TJSONStreamEvent Read FBeforeStreamObject Write FBeforeStreamObject;
107 // Called After streaming an object with ObjectToJSON
108 Property AfterStreamObject : TJSONStreamEvent Read FAfterStreamObject Write FAfterStreamObject;
109 // Called whenever a property was streamed. If Res is nil on return, no property is added.
110 Property OnStreamProperty : TJSONPropertyEvent Read FOnStreamProperty Write FOnStreamProperty;
111 // Property name to use when streaming child components. Default is "Children"
112 Property ChildProperty : String Read GetChildProperty Write FChildProperty Stored IsChildStored;
113 end;
114
115 { TJSONDeStreamer }
116 TJSONRestorePropertyEvent = Procedure (Sender : TObject; AObject : TObject; Info : PPropInfo; AValue : TJSONData; Var Handled : Boolean) of object;
117 TJSONPropertyErrorEvent = Procedure (Sender : TObject; AObject : TObject; Info : PPropInfo; AValue : TJSONData; Error : Exception; Var Continue : Boolean) of object;
118 TJSONGetObjectEvent = Procedure (Sender : TOBject; AObject : TObject; Info : PPropInfo; AData : TJSONObject; DataName : TJSONStringType; Var AValue : TObject);
119 TJSONDestreamOption = (jdoCaseInsensitive,jdoIgnorePropertyErrors,jdoIgnoreNulls,jdoNullClearsProperty);
120 TJSONDestreamOptions = set of TJSONDestreamOption;
121
122 TJSONDeStreamer = Class(TJSONFiler)
123 private
124 FAfterReadObject: TJSONStreamEvent;
125 FBeforeReadObject: TJSONStreamEvent;
126 FDateTimeFormat: String;
127 FOnGetObject: TJSONGetObjectEvent;
128 FOnPropError: TJSONpropertyErrorEvent;
129 FOnRestoreProp: TJSONRestorePropertyEvent;
130 FOptions: TJSONDestreamOptions;
131 procedure DeStreamClassProperty(AObject: TObject; PropInfo: PPropInfo; PropData: TJSONData);
132 function GetCaseInsensitive: Boolean;
133 procedure SetCaseInsensitive(AValue: Boolean);
134 protected
135 // Try to parse a date.
136 Function ExtractDateTime(S : String): TDateTime;
137 function GetObject(AInstance : TObject; const APropName: TJSONStringType; D: TJSONObject; PropInfo: PPropInfo): TObject;
138 procedure DoClearProperty(AObject: TObject; PropInfo: PPropInfo); virtual;
139 procedure DoRestoreProperty(AObject: TObject; PropInfo: PPropInfo; PropData: TJSONData); virtual;
140 function DoMapProperty(AObject: TObject; PropInfo: PPropInfo; JSON: TJSONObject): TJSONData; virtual;
141 procedure DoBeforeReadObject(Const JSON: TJSONObject; AObject: TObject); virtual;
142 procedure DoAfterReadObject(Const JSON: TJSONObject; AObject: TObject); virtual;
143 Function ObjectFromString(Const JSON : TJSONStringType) : TJSONData; virtual;
144 procedure RestoreProperty(AObject: TObject; PropInfo: PPropInfo; PropData: TJSONData);
145 Public
146 Constructor Create(AOwner : TComponent); override;
147 Destructor Destroy; override;
148 // Convert JSON object to properties of AObject
149 Procedure JSONToObject(Const JSON : TJSONStringType; AObject : TObject); overload;
150 Procedure JSONToObject(Const JSON : TJSONObject; AObject : TObject); overload;
151 // Convert JSON object/array to collection.
152 Procedure JSONToCollection(Const JSON : TJSONStringType; ACollection : TCollection); overload;
153 Procedure JSONToCollection(Const JSON : TJSONData; ACollection : TCollection); overload;
154 // Convert JSON array/object/string to TStrings
155 Procedure JSONToStrings(Const JSON : TJSONStringType; AStrings : TSTrings); overload;
156 Procedure JSONToStrings(Const JSON : TJSONData; AStrings : TSTrings); overload;
157 // Convert JSON data to a variant. Supports simple data types and arrays.
158 Function JSONToVariant(Data: TJSONData): Variant; overload;
159 Function JSONToVariant(Data: TJSONStringType): Variant; overload;
160 // Triggered at the start of each call to JSONToObject
161 Property BeforeReadObject : TJSONStreamEvent Read FBeforeReadObject Write FBeforeReadObject;
162 // Triggered at the end of each call to JSONToObject (not if exception happens)
163 Property AfterReadObject : TJSONStreamEvent Read FAfterReadObject Write FAfterReadObject;
164 // Called when a property will be restored. If 'Handled' is True on return, property is considered restored.
165 Property OnRestoreProperty : TJSONRestorePropertyEvent Read FOnRestoreProp Write FOnRestoreProp;
166 // Called when an error occurs when restoring a property. If Continue is False on return, exception is re-raised.
167 Property OnPropertyError : TJSONpropertyErrorEvent Read FOnPropError Write FOnPropError;
168 // Called when a object-typed property must be restored, and the property is Nil. Must return an instance for the property.
169 // Published Properties of the instance will be further restored with available data.
170 Property OngetObject : TJSONGetObjectEvent Read FOnGetObject Write FOnGetObject;
171 // JSON is by definition case sensitive. Should properties be looked up case-insentive ?
172 Property CaseInsensitive : Boolean Read GetCaseInsensitive Write SetCaseInsensitive ; /// deprecated;
173 // DateTime format. If not set, RFC3339DateTimeFormat is assumed.
174 // If set, it will be used as an argument to ScanDateTime. If that fails, StrToDateTime is used.
175 Property DateTimeFormat : String Read FDateTimeFormat Write FDateTimeFormat;
176 // Options overning the behaviour
177 Property Options : TJSONDestreamOptions Read FOptions Write FOptions;
178 end;
179
180 EJSONRTTI = Class(Exception);
181
182
183 implementation
184
185 uses dateutils, variants, rtlconsts;
186
187 ResourceString
188 SErrUnknownPropertyKind = 'Unknown property kind for property : "%s"';
189 SErrUnsupportedPropertyKind = 'Unsupported property kind for property: "%s"';
190 SErrUnsupportedVariantType = 'Unsupported variant type : %d';
191 SErrUnsupportedArrayType = 'JSON array cannot be streamed to object of class "%s"';
192 SErrUnsupportedJSONType = 'Cannot destream object from JSON data of type "%s"';
193 SErrUnsupportedCollectionType = 'Unsupported JSON type for collections: "%s"';
194 SErrUnsupportedCollectionItemType = 'Array element %d is not a valid type for a collection item: "%s"';
195 SErrUnsupportedStringsItemType = 'Array element %d is not a valid type for a stringlist item: "%s"';
196 SErrUnsupportedStringsType = 'Unsupported JSON type for stringlists: "%s"';
197 SErrUnsupportedStringsObjectType = 'Object Element %s is not a valid type for a stringlist object: "%s"';
198 SErrUnSupportedEnumDataType = 'Unsupported JSON type for enumerated property "%s" : "%s"';
199 SErrUnsupportedVariantJSONType = 'Unsupported JSON type for variant value : "%s"';
200 SErrUnsupportedObjectData = 'Unsupported JSON type for object property: "%s"';
201
202 { TStreamChildrenHelper }
203
204 Type
205 TSet = set of 0..31; // Used to (de)stream set properties.
206
207 TStreamChildrenHelper = Class
208 Private
209 FChildren : TJSONArray;
210 FStreamer:TJSONStreamer;
211 procedure StreamChild(AChild: TComponent);
212 public
213 Function StreamChildren(AComponent : TComponent; AStreamer : TJSONStreamer): TJSONArray;
214 end;
215
216 THackComponent = Class(TComponent);
217
218 { TJSONDeStreamer }
219
220 function TJSONDeStreamer.ObjectFromString(const JSON: TJSONStringType): TJSONData;
221
222 begin
223 With TJSONParser.Create(JSON,[]) do
224 try
225 Result:=Parse;
226 finally
227 Free;
228 end;
229 end;
230
231 constructor TJSONDeStreamer.Create(AOwner: TComponent);
232 begin
233 inherited Create(AOwner);
234 end;
235
236 destructor TJSONDeStreamer.Destroy;
237 begin
238 inherited Destroy;
239 end;
240
241 procedure TJSONDeStreamer.JSONToObject(const JSON: TJSONStringType;
242 AObject: TObject);
243
244 Var
245 D : TJSONData;
246
247 begin
248 D:=ObjectFromString(JSON);
249
250 if not Assigned(D) then
251 Exit;
252
253 try
254 If D.JSONType=jtObject then
255 JSONToObject(D as TJSONObject,AObject)
256 else if D.JSONType=jtArray then
257 begin
258 If AObject is TStrings then
259 JSONToStrings(D,AObject as TSTrings)
260 else if AObject is TCollection then
261 JSONTOCollection(D,AObject as TCollection)
262 else
263 Error(SErrUnsupportedArrayType,[AObject.ClassName])
264 end
265 else if (D.JSONType=jtString) and (AObject is TStrings) then
266 JSONToStrings(D,AObject as TStrings)
267 else
268 Error(SErrUnsupportedJSONType,[JSONTypeName(D.JSONType)]);
269 finally
270 FreeAndNil(D);
271 end;
272 end;
273
274 function TJSONDeStreamer.JSONToVariant(Data: TJSONData): Variant;
275
276 Var
277 I : integer;
278
279 begin
280 Case Data.JSONType of
281 jtNumber :
282 Case TJSONNumber(Data).NumberType of
283 ntFloat : Result:=Data.AsFloat;
284 ntInteger : Result:=Data.AsInteger;
285 ntInt64 : Result:=Data.Asint64;
286 ntQWord : Result:=Data.AsQWord;
287 end;
288 jtString :
289 Result:=Data.AsString;
290 jtBoolean:
291 Result:=Data.AsBoolean;
292 jtNull:
293 Result:=Null;
294 jtArray :
295 begin
296 Result:=VarArrayCreate([0,Data.Count-1],varVariant);
297 For I:=0 to Data.Count-1 do
298 Result[i]:=JSONToVariant(Data.Items[i]);
299 end;
300 else
301 Error(SErrUnsupportedVariantJSONType,[GetEnumName(TypeInfo(TJSONType),Ord(Data.JSONType))]);
302 end;
303 end;
304
305 function TJSONDeStreamer.JSONToVariant(Data: TJSONStringType): Variant;
306
307 Var
308 D : TJSONData;
309
310 begin
311 D:=ObjectFromString(Data);
312 try
313 Result:=JSONToVariant(D);
314 finally
315 D.Free;
316 end;
317 end;
318
319 procedure TJSONDeStreamer.DeStreamClassProperty(AObject : TObject;PropInfo : PPropInfo; PropData : TJSONData);
320
321 Var
322 O : TObject;
323
324 begin
325 O:=GetObjectProp(AObject,PropInfo);
326 If O is TStrings then
327 JSONToStrings(PropData,O as TStrings)
328 else if (O is TCollection) then
329 JSONToCollection(PropData,O as TCollection)
330 else
331 begin
332 If (O=Nil) then
333 begin
334 If (PropData.JSONType=jtString) then
335 O:=GetObject(AObject,PropData.AsString,Nil,PropInfo)
336 else if (PropData.JSONType=jtObject) then
337 O:=GetObject(AObject,'',PropData as TJSONObject,PropInfo)
338 else
339 Error(SErrUnsupportedObjectData,[JsonTypeName(PropData.JSONType){GetEnumName(TypeInfo(TJSONType),Ord(PropData.JSONType))}]);
340 SetObjectProp(AObject,PropInfo,O);
341 end;
342 If (O<>Nil) and (PropData.JSONType=jtObject) then
343 JSONToObject(PropData as TJSONObject,O);
344 end;
345 end;
346
347 function TJSONDeStreamer.GetCaseInsensitive: Boolean;
348 begin
349 Result:=jdoCaseInsensitive in Options;
350 end;
351
352 procedure TJSONDeStreamer.SetCaseInsensitive(AValue: Boolean);
353 begin
354 if AValue then
355 Include(Foptions,jdoCaseInsensitive)
356 else
357 Exclude(Foptions,jdoCaseInsensitive);
358 end;
359
360 function TJSONDeStreamer.ExtractDateTime(S: String): TDateTime;
361
362 Var
363 Fmt : String;
364 E,fmtSpecified : Boolean;
365
366 begin
367 E:=False;
368 FMT:=DateTimeFormat;
369 fmtSpecified:=Fmt<>'';
370 if Not fmtSpecified then
371 FMT:=RFC3339DateTimeFormat;
372 // TODO: ScanDatetime in delphi
373 { Try
374 // No TryScanDateTime
375 Result:=ScanDatetime(FMT,S);
376 except
377 if fmtSpecified then
378 Raise
379 else
380 E:=True;
381 end;
382 if E then}
383 if not TryStrToDateTime(S,Result) then
384 if not TryStrToDate(S,Result) then
385 if not TryStrToTime(S,Result) then
386 Raise EConvertError.CreateFmt(SInvalidDateTime,[S]);
387 // ExtractDateTime(PropData.AsString)
388 end;
389
390 procedure TJSONDeStreamer.RestoreProperty(AObject : TObject;PropInfo : PPropInfo; PropData : TJSONData);
391
392 Var
393 B : Boolean;
394
395 begin
396 try
397 B:=Not Assigned(FOnRestoreProp);
398 If Not B then
399 begin
400 FOnRestoreProp(Self,AObject,PropInfo,PropData,B);
401 If B then
402 exit;
403 end;
404 if (PropData.JSONType<>jtNull) then
405 DoRestoreProperty(AObject,PropInfo,PropData)
406 else if (jdoNullClearsProperty in Options) then
407 DoClearProperty(aObject,PropInfo)
408 else if not (jdoIgnoreNulls in Options) then
409 DoRestoreProperty(AObject,PropInfo,PropData)
410
411 except
412 On E : Exception do
413 If Assigned(FOnPropError) then
414 begin
415 B:=False;
416 FOnPropError(Self,AObject,PropInfo,PropData,E,B);
417 If Not B then
418 Raise;
419 end
420 else if Not (jdoIgnorePropertyErrors in Options) then
421 Raise;
422 end;
423 end;
424
425 procedure TJSONDeStreamer.DoClearProperty(AObject : TObject;PropInfo : PPropInfo);
426
427 Var
428 PI : PPropInfo;
429 TI : PTypeInfo;
430 begin
431 PI:=PropInfo;
432 TI:=PropInfo^.PropType^;
433 case TI^.Kind of
434 tkUnknown :
435 Error(SErrUnknownPropertyKind,[PI^.Name]);
436 tkInteger,
437 tkEnumeration,
438 tkSet,
439 tkChar,
440 tkWChar:
441 SetOrdProp(AObject,PI,0);
442 ///tkBool,
443 ///tkQWord,
444 ///tkUChar,
445 tkInt64 :
446 SetInt64Prop(AObject,PI,0);
447 tkFloat :
448 SetFloatProp(AObject,PI,0.0);
449 tkString,
450 tkLString:
451 SetAnsiStrProp(AObject,PI,'');
452 tkWString :
453 SetWideStrProp(AObject,PI,'');
454 tkVariant:
455 SetVariantProp(AObject,PI,Null);
456 tkClass:
457 SetOrdProp(AObject,PI,0);
458 tkUString :
459 SetStrProp(AObject,PI,'');
460 else
461 {
462 tkObject,
463 tkArray,
464 tkRecord,
465 tkInterface,
466 tkDynArray,
467 tkInterfaceRaw,
468 tkProcVar,
469 tkMethod }
470 Error(SErrUnsupportedPropertyKind,[PI^.Name]);
471 end;
472 end;
473
474 procedure TJSONDeStreamer.DoRestoreProperty(AObject : TObject;PropInfo : PPropInfo; PropData : TJSONData);
475
476 Var
477 PI : PPropInfo;
478 TI : PTypeInfo;
479 I,J,S : Integer;
480 A : TJSONArray;
481 JS : TJSONStringType;
482 begin
483 PI:=PropInfo;
484 TI:=PropInfo^.PropType^;
485 case TI^.Kind of
486 tkUnknown :
487 Error(SErrUnknownPropertyKind,[PI^.Name]);
488 tkInteger :
489 SetOrdProp(AObject,PI,PropData.AsInteger);
490 tkInt64 :
491 SetInt64Prop(AObject,PI,PropData.AsInt64);
492 tkEnumeration :
493 begin
494 if (PropData.JSONType=jtNumber) then
495 I:=PropData.AsInteger
496 else if PropData.JSONType=jtString then
497 I:=GetEnumValue(TI,PropData.AsString)
498 else if PropData.JSONType=jtBoolean then
499 I:=GetEnumValue(TI,PropData.AsString)
500 else
501 Error(SErrUnSupportedEnumDataType,[PI^.Name,GetEnumName(TypeInfo(TJSONType),Ord(PropData.JSONType))]);
502 SetOrdProp(AObject,PI,I);
503 end;
504 tkFloat :
505 begin
506 if (TI=TypeInfo(TDateTime)) and (PropData.JSONType=jtString) then
507 SetFloatProp(AObject,PI,ExtractDateTime(PropData.AsString))
508 else
509 SetFloatProp(AObject,PI,PropData.AsFloat)
510 end;
511 tkSet :
512 If PropData.JSONType=jtString then
513 SetSetProp(AObject,PI,PropData.AsString)
514 else if (PropData.JSONType=jtArray) then
515 begin
516 A:=PropData as TJSONArray;
517 TI:=GetTypeData(TI)^.CompType^;
518 S:=0;
519 For I:=0 to A.Count-1 do
520 begin
521 if A.types[i]=jtNumber then
522 J:=A.Integers[i]
523 else
524 J:=GetEnumValue(TI,A.strings[i]);
525 TSet(S):=TSet(S)+[j];
526 end;
527 SetOrdProp(AObject,PI,S);
528 end;
529 tkChar:
530 begin
531 JS:=PropData.AsString;
532 If (JS<>'') then
533 SetOrdProp(AObject,PI,Ord(JS[1]));
534 end;
535 tkString,
536 tkLString:
537 SetStrProp(AObject,PI,PropData.AsString);
538 tkWString :
539 SetWideStrProp(AObject,PI,PropData.AsUnicodeString);
540 tkVariant:
541 SetVariantProp(AObject,PI,JSONToVariant(PropData));
542 tkClass:
543 DeStreamClassProperty(AObject,PI,PropData);
544 tkWChar :
545 begin
546 JS:=PropData.asString;
547 If (JS<>'') then
548 SetOrdProp(AObject,PI,Ord(JS[1]));
549 end;
550 /// tkBool :
551 /// SetOrdProp(AObject,PI,Ord(PropData.AsBoolean));
552 /// tkQWord :
553 /// SetOrdProp(AObject,PI,Trunc(PropData.AsFloat));
554 /// tkObject,
555 tkArray,
556 tkRecord,
557 tkInterface,
558 tkDynArray,
559 /// tkInterfaceRaw,
560 /// tkProcVar,
561 tkMethod :
562 Error(SErrUnsupportedPropertyKind,[PI^.Name]);
563 tkUString :
564 SetUnicodeStrProp(AObject,PI,PropData.AsUnicodeString);
565 /// tkUChar:
566 /// begin
567 /// JS:=PropData.asString;
568 /// If (JS<>'') then
569 /// SetOrdProp(AObject,PI,Ord(JS[1]));
570 /// end;
571 end;
572 end;
573
574 function TJSONDeStreamer.DoMapProperty(AObject: TObject; PropInfo: PPropInfo; JSON: TJSONObject): TJSONData;
575 var
576 J: Integer;
577 begin
578 J := JSON.IndexOfName(PropInfo^.Name,(jdoCaseInsensitive in Options));
579 if J > -1 then
580 Result := JSON.Items[J]
581 else
582 Result := nil;
583 end;
584
585 procedure TJSONDeStreamer.DoBeforeReadObject(Const JSON: TJSONObject; AObject: TObject);
586 begin
587 If Assigned(FBeforeReadObject) then
588 FBeforeReadObject(Self,AObject,JSON);
589 end;
590
591 procedure TJSONDeStreamer.DoAfterReadObject(Const JSON: TJSONObject; AObject: TObject);
592 begin
593 If Assigned(FAfterReadObject) then
594 FAfterReadObject(Self,AObject,JSON)
595 end;
596
597 procedure TJSONDeStreamer.JSONToObject(const JSON: TJSONObject; AObject: TObject
598 );
599 Var
600 I : Integer;
601 PIL : TPropInfoList;
602 JD: TJSONData;
603
604 begin
605 DoBeforeReadObject(JSON, AObject);
606 If (AObject is TStrings) then
607 JSONToStrings(JSON,AObject as TStrings)
608 else If (AObject is TCollection) then
609 JSONToCollection(JSON, AObject as TCollection)
610 else
611 begin
612 Pil:=TPropInfoList.Create(AObject,tkProperties);
613 try
614 For I:=0 to PIL.Count-1 do
615 begin
616 JD:=DoMapProperty(AObject, Pil.Items[i], JSON);
617 If Assigned(JD) then
618 RestoreProperty(AObject,PIL.Items[i],JD);
619 end;
620 finally
621 FreeAndNil(PIL);
622 end;
623 end;
624 DoAfterReadObject(JSON, AObject);
625 end;
626
627 procedure TJSONDeStreamer.JSONToCollection(const JSON: TJSONStringType;
628 ACollection: TCollection);
629 Var
630 D : TJSONData;
631
632 begin
633 D:=ObjectFromString(JSON);
634 try
635 if Assigned(D) then
636 JSONToCollection(D,ACollection);
637 finally
638 D.Free;
639 end;
640 end;
641
642 procedure TJSONDeStreamer.JSONToCollection(const JSON: TJSONData;
643 ACollection: TCollection);
644
645 Var
646 I : integer;
647 A : TJSONArray;
648
649 begin
650 If (JSON.JSONType=jtArray) then
651 A:=JSON As TJSONArray
652 else if JSON.JSONType=jtObject then
653 A:=(JSON as TJSONObject).Arrays['Items']
654 else
655 Error(SErrUnsupportedCollectionType,[JSONTypeName(JSON.JSONType)]);
656 ACollection.Clear;
657 For I:=0 to A.Count-1 do
658 If (A.Types[i]<>jtObject) then
659 Error(SErrUnsupportedCollectionItemType,[I,JSONTypeName(A.Types[I])])
660 else
661 JSONToObject(A.Objects[i],ACollection.Add);
662 end;
663
664 procedure TJSONDeStreamer.JSONToStrings(const JSON: TJSONStringType;
665 AStrings: TSTrings);
666 Var
667 D : TJSONData;
668
669 begin
670 D:=ObjectFromString(JSON);
671 try
672 JSONToStrings(D,AStrings);
673 finally
674 D.Free;
675 end;
676 end;
677
678 function TJSONDeStreamer.GetObject(AInstance: TObject;
679 const APropName: TJSONStringType; D: TJSONObject; PropInfo: PPropInfo
680 ): TObject;
681
682 Var
683 C : TClass;
684
685 begin
686 Result:=Nil;
687 If Assigned(FOnGetObject) then
688 FOnGetObject(Self,AInstance,PropInfo,D,APropName,Result);
689 If (Result=Nil) and (AInstance is TComponent) and Assigned(PropInfo) then
690 begin
691 C:=GetTypeData(Propinfo^.PropType^)^.ClassType;
692 If C.InheritsFrom(TComponent) then
693 Result:=TComponentClass(C).Create(TComponent(AInstance));
694 end;
695 end;
696
697 procedure TJSONDeStreamer.JSONToStrings(const JSON: TJSONData;
698 AStrings: TSTrings);
699
700 Var
701 O : TJSONObject;
702 D : TJSONData;
703 I : Integer;
704 IO : TObject;
705 N : TJSONStringType;
706
707 begin
708 Case JSON.JSONType of
709 jtString:
710 AStrings.Text:=JSON.AsString;
711 jtArray:
712 begin
713 AStrings.Clear;
714 For I:=0 to JSON.Count-1 do
715 begin
716 if not (JSON.Items[i].JSONType=jtString) then
717 Error(SErrUnsupportedStringsItemType,[i,JSONTypeName(JSON.Items[i].JSONType)]);
718 AStrings.Add(JSON.Items[i].AsString);
719 end;
720 end;
721 jtObject:
722 begin
723 O:=JSON As TJSONObject;
724 If (O.Count=1) and (O.Names[0]='Strings') and (O.Items[0].JSONType=jtArray) then
725 JSONToStrings(O.Items[0],AStrings)
726 else
727 begin
728 AStrings.Clear;
729 For I:=0 to O.Count-1 do
730 begin
731 D:=O.Items[i];
732 N:=O.Names[i];
733 If D.JSONType=jtNull then
734 IO:=Nil
735 else if D.JSONType=jtObject then
736 IO:=GetObject(AStrings,N,TJSONOBject(D),Nil)
737 else
738 Error(SErrUnsupportedStringsObjectType,[D,JSONTypeName(D.JSONType)]);
739 AStrings.AddObject(O.Names[i],IO);
740 end;
741 end;
742 end;
743 else
744 Error(SErrUnsupportedStringsType,[JSONTypeName(JSON.JSONType)]);
745 end;
746 end;
747
748 Procedure TStreamChildrenHelper.StreamChild(AChild : TComponent);
749
750 begin
751 FChildren.Add(FStreamer.ObjectToJSON(AChild));
752 end;
753
754 Function TStreamChildrenHelper.StreamChildren(AComponent : TComponent; AStreamer : TJSONStreamer): TJSONArray;
755
756 begin
757 FStreamer:=AStreamer;
758 Result:=TJSONArray.Create;
759 try
760 FChildren:=Result;
761 THackComponent(AComponent).GetChildren(StreamChild, AComponent);
762 except
763 FreeAndNil(Result);
764 Raise;
765 end;
766 end;
767
768 { TJSONFiler }
769
770 procedure TJSONFiler.Error(Const Msg: String);
771 begin
772 Raise EJSONRTTI.Create(Name+' : '+Msg);
773 end;
774
775 procedure TJSONFiler.Error(Const FMT: String; Args: array of const);
776 begin
777 Raise EJSONRTTI.CreateFmt(Name+' : '+FMT,Args);
778 end;
779
780 { TJSONStreamer }
781
782 constructor TJSONStreamer.Create(AOwner: TComponent);
783 begin
784 Inherited;
785 end;
786
787 destructor TJSONStreamer.Destroy;
788 begin
789 Inherited;
790 end;
791
792
793 Function TJSONStreamer.StreamChildren(AComp : TComponent) : TJSONArray;
794
795 begin
796 With TStreamChildrenHelper.Create do
797 try
798 Result:=StreamChildren(AComp,Self);
799 finally
800 Free;
801 end;
802 end;
803
804 function TJSONStreamer.GetChildProperty: String;
805 begin
806 Result:=FChildProperty;
807 If (Result='') then
808 Result:='Children';
809 end;
810
811 function TJSONStreamer.IsChildStored: boolean;
812 begin
813 Result:=(GetChildProperty<>'Children');
814 end;
815
816 function TJSONStreamer.ObjectToJSON(Const AObject: TObject): TJSONObject;
817
818 Var
819 PIL : TPropInfoList;
820 PD : TJSONData;
821 I : Integer;
822
823 begin
824 Result:=Nil;
825 If (AObject=Nil) then
826 Exit;
827 Result:=TJSONObject.Create;
828 try
829 If Assigned(FBeforeStreamObject) then
830 FBeforeStreamObject(Self,AObject,Result);
831 If AObject is TStrings then
832 Result.Add('Strings',StreamTStrings(Tstrings(AObject)))
833 else If AObject is TCollection then
834 Result.Add('Items',StreamCollection(TCollection(AObject)))
835 else If AObject is TObjectList then
836 Result.Add('Objects',StreamObjectList(TObjectList(AObject)))
837 else if (jsoStreamTlist in Options) and (AObject is TList) then
838 Result.Add('Objects', StreamTList(TList(AObject)))
839 else
840 begin
841 PIL:=TPropInfoList.Create(AObject,tkProperties);
842 try
843 For I:=0 to PIL.Count-1 do
844 begin
845 PD:=StreamProperty(AObject,PIL.Items[i]);
846 If (PD<>Nil) then begin
847 if jsoLowerPropertyNames in Options then
848 Result.Add(LowerCase(PIL.Items[I]^.Name),PD)
849 else
850 Result.Add(PIL.Items[I]^.Name,PD);
851 end;
852 end;
853 finally
854 FReeAndNil(Pil);
855 end;
856 If (jsoStreamChildren in Options) and (AObject is TComponent) then
857 Result.Add(ChildProperty,StreamChildren(TComponent(AObject)));
858 If Assigned(FAfterStreamObject) then
859 FAfterStreamObject(Self,AObject,Result);
860 end;
861 except
862 FreeAndNil(Result);
863 Raise;
864 end;
865 end;
866
867 function TJSONStreamer.StreamProperty(Const AObject: TObject; Const PropertyName : String): TJSONData;
868
869 begin
870 Result:=StreamProperty(AObject,GetPropInfo(AObject,PropertyName));
871 end;
872
873 Function TJSONStreamer.StreamVariant(Const Data : Variant): TJSONData;
874
875 Var
876 A : TJSONArray;
877 I : Integer;
878
879 begin
880 Result:=Nil;
881 If VarIsArray(Data) then
882 begin
883 A:=TJSONArray.Create;
884 try
885 For I:=VarArrayLowBound(Data,1) to VarArrayHighBound(Data,1) do
886 A.Add(StreamVariant(Data[i]));
887 except
888 FreeAndNil(A);
889 Raise;
890 end;
891 Exit(A);
892 end;
893 If VarIsEmpty(Data) or VarisNull(Data) or (Data=UnAssigned) then
894 Exit(TJSONNull.Create);
895 Case VarType(Data) of
896 varshortint,
897 varbyte,
898 varword,
899 varsmallint,
900 varinteger :
901 Result:=TJSONIntegerNumber.Create(Data);
902 varlongword,
903 varint64 :
904 Result:=TJSONInt64Number.Create(Data);
905 /// vardecimal,
906 varUInt64,
907 varsingle,
908 vardouble,
909 varCurrency :
910 Result:=TJSONFloatNumber.Create(Data);
911 varString,
912 varolestr :
913 Result:=TJSONString.Create(Data);
914 varboolean :
915 Result:=TJSONBoolean.Create(Data);
916 varDate :
917 if jsoDateTimeAsString in Options then
918 Result:=FormatDateProp(Data)
919 else
920 Result:=TJSONFloatNumber.Create(Data);
921 else
922 Error(SErrUnsupportedVariantType,[VarType(Data)])
923 end;
924 end;
925
926 function TJSONStreamer.ObjectToJSONString(AObject: TObject): TJSONStringType;
927
928 Var
929 O : TJSONData;
930
931 begin
932 O:=ObjectToJSON(AObject);
933 try
934 if (jsoUseFormatString in Options) then
935 Result:=O.FormatJSON()
936 else
937 Result:=O.AsJSON;
938 finally
939 FreeAndNil(O);
940 end;
941 end;
942
943 function TJSONStreamer.StringsToJSON(Const Strings: TStrings; AsObject: Boolean = False): TJSONStringType;
944
945 Var
946 D : TJSONData;
947
948 begin
949 If ASObject then
950 D:=StreamTSTringsObject(Strings)
951 else
952 D:=StreamTStringsArray(Strings);
953 try
954 if (jsoUseFormatString in Options) then
955 Result:=D.FormatJSON
956 else
957 Result:=D.AsJSON;
958 finally
959 FreeAndNil(D);
960 end;
961 end;
962
963 function TJSONStreamer.CollectionToJSON(const ACollection: TCollection
964 ): TJSONStringType;
965
966 Var
967 D : TJSONArray;
968
969 begin
970 D:=StreamCollection(ACollection);
971 try
972 if (jsoUseFormatString in Options) then
973 Result:=D.FormatJSON()
974 else
975 Result:=D.AsJSON;
976 finally
977 FreeAndNil(D);
978 end;
979 end;
980
981 function TJSONStreamer.VariantToJSON(const Data: Variant): TJSONStringType;
982
983 Var
984 D : TJSONData;
985
986 begin
987 D:=StreamVariant(Data);
988 try
989 if (jsoUseFormatString in Options) then
990 Result:=D.FormatJSON()
991 else
992 Result:=D.AsJSON;
993 finally
994 FreeAndNil(D);
995 end;
996 end;
997
998 function TJSONStreamer.StreamTList(const AList: TList): TJSONArray;
999 var
1000 I : Integer;
1001 o : TJSONObject;
1002 begin
1003 Result:=TJSONArray.Create;
1004 try
1005 for I:=0 to AList.Count-1 do begin
1006 o := ObjectToJSON(TObject(AList.Items[i]));
1007 if Assigned(o) then
1008 Result.Add(o);
1009 end;
1010 except
1011 FreeAndNil(Result);
1012 Raise;
1013 end;
1014 end;
1015
1016 Function TJSONStreamer.StreamTStringsArray(Const AStrings : TStrings) : TJSONArray;
1017
1018 Var
1019 I : Integer;
1020
1021 begin
1022 Result:=TJSONArray.Create;
1023 try
1024 For I:=0 to AStrings.Count-1 do
1025 Result.Add(AStrings[i]);
1026 except
1027 FreeAndNil(Result);
1028 Raise;
1029 end;
1030 end;
1031
1032 function TJSONStreamer.StreamTStringsObject(Const AStrings: TStrings): TJSONObject;
1033
1034 Var
1035 I : Integer;
1036 O : TJSONData;
1037
1038 begin
1039 Result:=TJSONObject.Create;
1040 try
1041 For I:=0 to AStrings.Count-1 do
1042 begin
1043 O:=ObjectToJSON(AStrings.Objects[i]);
1044 If O=Nil then
1045 O:=TJSONNull.Create;
1046 Result.Add(AStrings[i],O);
1047 end;
1048 except
1049 FreeAndNil(Result);
1050 Raise;
1051 end;
1052 end;
1053
1054 function TJSONStreamer.StreamTStrings(Const AStrings: TStrings): TJSONData;
1055 begin
1056 If jsoTStringsAsArray in Options then
1057 Result:=StreamTStringsArray(AStrings)
1058 else If jsoTStringsAsObject in Options then
1059 Result:=StreamTStringsObject(AStrings)
1060 else
1061 Result:=TJSONString.Create(AStrings.Text);
1062 end;
1063
1064
1065 Function TJSONStreamer.StreamCollection(Const ACollection : TCollection) : TJSONArray;
1066
1067 Var
1068 I : Integer;
1069
1070 begin
1071 Result:=TJSONArray.Create;
1072 try
1073 For I:=0 to ACollection.Count-1 do
1074 Result.Add(ObjectToJSON(ACollection.Items[i]));
1075 except
1076 FreeAndNil(Result);
1077 Raise;
1078 end;
1079 end;
1080
1081 function TJSONStreamer.StreamObjectList(const AnObjectList: TObjectList): TJSONArray;
1082 Var
1083 I : Integer;
1084
1085 begin
1086 if not Assigned(AnObjectList) then
1087 Result:=Nil;
1088 Result:=TJSONArray.Create;
1089 try
1090 For I:=0 to AnObjectList.Count-1 do
1091 Result.Add(ObjectToJSON(AnObjectList.Items[i]));
1092 except
1093 FreeAndNil(Result);
1094 Raise;
1095 end;
1096 end;
1097
1098 function TJSONStreamer.StreamClassProperty(const AObject: TObject): TJSONData;
1099
1100
1101 begin
1102 Result:=Nil;
1103 If (AObject=Nil) then
1104 Result:=TJSONNull.Create()
1105 else if (AObject is TComponent) then
1106 begin
1107 if (csSubComponent in TComponent(AObject).ComponentStyle) or (jsoComponentsInline in Options) then
1108 Result:=ObjectToJSON(AObject)
1109 else
1110 Result:=TJSONString.Create(TComponent(AObject).Name);
1111 end
1112 else if (AObject is TStrings) then
1113 Result:=StreamTStrings(TStrings(AObject))
1114 else if (AObject is TCollection) then
1115 Result:=StreamCollection(TCollection(Aobject))
1116 else If AObject is TObjectList then
1117 Result:=StreamObjectList(TObjectList(AObject))
1118 else // Normally, this is only TPersistent.
1119 Result:=ObjectToJSON(AObject);
1120 end;
1121
1122 function TJSONStreamer.StreamProperty(Const AObject: TObject; PropertyInfo: PPropInfo): TJSONData;
1123
1124 Var
1125 PI : PPropInfo;
1126 PT : PTypeInfo;
1127 S,I : integer;
1128
1129 begin
1130 Result:=Nil;
1131 PI:=PropertyInfo;
1132 PT:=PI^.PropType^;
1133 Case PT^.Kind of
1134 tkUnknown :
1135 Error(SErrUnknownPropertyKind,[PI^.Name]);
1136 tkInteger :
1137 Result:=TJSONIntegerNumber.Create(GetOrdProp(AObject,PI));
1138 tkEnumeration :
1139 if jsoEnumeratedAsInteger in Options then
1140 Result:=TJSONIntegerNumber.Create(GetOrdProp(AObject,PI))
1141 else
1142 Result:=TJSONString.Create(GetEnumName(PT,GetOrdProp(AObject,PI)));
1143 tkFloat :
1144 if (PT=TypeInfo(TDateTime)) and (jsoDateTimeAsString in Options) then
1145 Result:=FormatDateProp(GetFloatProp(AObject,PI))
1146 else
1147 Result:=TJSONFloatNumber.Create(GetFloatProp(AObject,PI));
1148 tkSet :
1149 If jsoSetAsString in Options then
1150 Result:=TJSONString.Create(GetSetProp(AObject,PI,jsoSetBrackets in Options))
1151 else
1152 begin
1153 PT:=GetTypeData(PT)^.CompType^;
1154 S:=GetOrdProp(AObject,PI);
1155 Result:=TJSONArray.Create;
1156 try
1157 for i:=0 to 31 do
1158 if (i in TSet(S)) then
1159 if jsoSetEnumeratedAsInteger in Options then
1160 TJSONArray(Result).Add(i)
1161 else
1162 TJSONArray(Result).Add(GetEnumName(PT, i));
1163 except
1164 FreeAndNil(Result);
1165 Raise;
1166 end;
1167 end;
1168 tkChar:
1169 Result:=TJSONString.Create(Char(GetOrdProp(AObject,PI)));
1170 tkString,
1171 tkLString:
1172 /// tkAString:
1173 Result:=TJSONString.Create(GetStrProp(AObject,PI));
1174 tkWString :
1175 Result:=TJSONString.Create(GetWideStrProp(AObject,PI));
1176 tkVariant:
1177 Result:=StreamVariant(GetVariantProp(AObject,PI));
1178 tkClass:
1179 Result:=StreamClassProperty(GetObjectProp(AObject,PI));
1180 tkWChar :
1181 Result:=TJSONString.Create(WideChar(GetOrdProp(AObject,PI)));
1182 /// tkBool :
1183 /// Result:=TJSONBoolean.Create(GetOrdProp(AObject,PropertyInfo)<>0);
1184 tkInt64 :
1185 { Note: using GetOrdProp will result in non-sense values on Delphi.
1186 And serializing e.g. "TComponent.Tag" on 64-bit systems relies on this. }
1187 Result:=TJSONInt64Number.Create(GetInt64Prop(AObject,PropertyInfo));
1188 /// tkQWord :
1189 /// Result:=TJSONFloatNumber.Create(GetOrdProp(AObject,PropertyInfo));
1190 /// tkObject :
1191 /// Result:=ObjectToJSON(GetObjectProp(AObject,PropertyInfo));
1192 tkArray,
1193 tkRecord,
1194 tkInterface,
1195 tkDynArray,
1196 /// tkInterfaceRaw,
1197 /// tkProcVar,
1198 tkMethod :
1199 Error(SErrUnsupportedPropertyKind,[PI^.Name]);
1200 tkUString :
1201 Result:=TJSONString.Create(GetWideStrProp(AObject,PI));
1202 /// tkUChar:
1203 /// Result:=TJSONString.Create(UnicodeChar(GetOrdProp(AObject,PI)));
1204 end;
1205 If Assigned(FOnStreamProperty) then
1206 FOnStreamProperty(Self,AObject,PI,Result);
1207 end;
1208
1209 function TJSONStreamer.FormatDateProp(Const DateTime: TDateTime): TJSONString;
1210
1211 Var
1212 S: String;
1213
1214 begin
1215 if (jsoCheckEmptyDateTime in Options) and (DateTime=0) then
1216 S:=''
1217 else if (DateTimeFormat<>'') then
1218 S:=FormatDateTime(DateTimeFormat,DateTime)
1219 else if (jsoLegacyDateTime in options) then
1220 begin
1221 if Frac(DateTime)=0 then
1222 S:=DateToStr(DateTime)
1223 else if Trunc(DateTime)=0 then
1224 S:=TimeToStr(DateTime)
1225 else
1226 S:=DateTimeToStr(DateTime);
1227 end
1228 else
1229 S:=FormatDateTime(RFC3339DateTimeFormat,DateTime);
1230
1231 Result:=TJSONString.Create(S);
1232 end;
1233
1234 end.
1235