Repository navigation
Expand file tree
/
Copy pathToJSON.pas
More file actions
79 lines (72 loc) · 2.44 KB
/
Copy pathToJSON.pas
File metadata and controls
79 lines (72 loc) · 2.44 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
unit ToJSON;
{*This unit takes any class and turns it to TJSONObject, names of properties are keys and their values are values. Due to use of RTTI context expect some increase in
size of project after compiling. Code supports basic variables, dynamic arrays and other classes inside given object or inside dynamic array *}
interface
uses
System.Classes,
System.SysUtils,
Winapi.Windows,
System.Json,
System.Rtti;
type
TToJson = class (TObject)
public
class procedure ToJson(IN_Class : TObject; var IO_Json : TJSONObject);
end;
implementation
{ TToJson }
class procedure TToJson.ToJson(IN_Class: TObject; var IO_Json: TJSONObject);
var
Context : TRttiContext;
ObjType : TRttiType;
Prop : TRttiProperty;
i : integer;
JSONArr : TJSONArray;
JSONObj : TJSONObject;
JSONPair : TJSONPair;
begin
Context := TRttiContext.Create;
ObjType := Context.GetType(IN_Class.ClassInfo) as TRttiInstanceType;
for Prop in ObjType.GetProperties do
begin
if Prop.IsReadable then
case Prop.PropertyType.TypeKind of
tkInteger :
begin
IO_Json.AddPair(Prop.Name, TJSONNumber.Create(Prop.GetValue(IN_Class).AsInteger()))
end;
tkFloat :
begin
IO_Json.AddPair(Prop.Name, TJSONNumber.Create(Prop.GetValue(IN_Class).AsExtended()))
end;
tkUString, tkString, tkChar :
begin
IO_Json.AddPair(Prop.Name, Prop.GetValue(IN_Class).AsString())
end;
tkVariant :
begin
IO_Json.AddPair(Prop.Name, TJSONNumber.Create(Prop.GetValue(IN_Class).AsVariant()))
end;
tkDynArray :
begin
JSONArr := TJSONArray.Create();
JSONPair := TJSONPair.Create(Prop.Name, JSONArr);
IO_Json.AddPair(JSONPair);
for i := 0 to Prop.GetValue(IN_Class).GetArrayLength -1 do
begin
JSONObj := TJSONObject.Create();
ToJson(Prop.GetValue(IN_Class).GetArrayElement(i).AsObject, JSONObj);
JSONArr.AddElement(JSONObj);
end;
end;
tkClass :
begin
JSONObj := TJSONObject.Create();
JSONPair := TJSONPair.Create(Prop.Name, JSONObj);
IO_Json.AddPair(JSONPair);
ToJson(Prop.GetValue(IN_Class).AsObject, JSONObj);
end;
end;
end;
end;
end.