-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathSystem.Json.Helper.pas
More file actions
117 lines (101 loc) · 3.16 KB
/
System.Json.Helper.pas
File metadata and controls
117 lines (101 loc) · 3.16 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
unit System.Json.Helper;
interface
Uses System.Classes, System.SysUtils, System.Rtti, System.TypInfo, System.Json;
type
TJsonRecord<T:Record> = class
public
class function ToJson(O: T): string;
class procedure FromJson(O:T;AJson:string);
end;
implementation
class procedure TJsonRecord<T>.FromJson(O: T; AJson: string);
var js:TJsonObject;
AContext : TRttiContext;
AField : TRttiField;
ARecord : TRttiRecordType;
AFldName : String;
AValue : TValue;
begin
js:= TJsonObject.ParseJSONValue(AJson) as TJsonObject;
try
AContext := TRttiContext.Create;
try
ARecord := AContext.GetType(TypeInfo(T)).AsRecord;
for AField in ARecord.GetFields do
begin
AFldName := AField.Name;
AValue := js.GetValue(AFldName);
AField.SetValue(@O,AValue);
end;
finally
AContext.free;
end;
finally
js.Free;
end;
end;
class function TJsonRecord<T>.ToJson(O: T): string;
var
AContext : TRttiContext;
AField : TRttiField;
ARecord : TRttiRecordType;
AFldName : String;
AValue : TValue;
ArrFields : TArray<TRttiField>;
i:integer;
js:TJsonObject;
begin
js := TJsonObject.Create;
AContext := TRttiContext.Create;
try
ARecord := AContext.GetType(TypeInfo(T)).AsRecord;
ArrFields := ARecord.GetFields;
i := 0;
for AField in ArrFields do
begin
AFldName := AField.Name;
AValue := AField.GetValue(@O);
try
if AValue.IsEmpty then
js.addPair(AFldName,'NULL')
else
case AField.FieldType.TypeKind of
tkInteger,tkInt64:
try
js.addPair(AFldName,TJSONNumber.Create(Avalue.AsInt64));
except
js.addPair(AFldName,TJSONNumber.Create(0));
end;
tkEnumeration:
js.addPair(AFldName,TJSONNumber.Create(Avalue.AsInteger));
tkFloat:
begin
if AField.FieldType.ToString.Equals('TDateTime') then
js.addPair(AFldName, FormatDateTime('yyyy-mm-dd HH:nn:ss', AValue.AsExtended))
else
if AField.FieldType.ToString.Equals('TDate') then
js.addPair(AFldName, FormatDateTime('yyyy-mm-dd', AValue.AsExtended))
else
if AField.FieldType.ToString.Equals('TTime') then
js.addPair(AFldName, FormatDateTime('HH:nn:ss', AValue.AsExtended))
else
try
js.addPair(AFldName,TJSONNumber.Create(Avalue.AsExtended));
except
js.addPair(AFldName,TJSONNumber.Create(0));
end;
end
else
js.addPair(AFldName,AValue.asString)
end;
except
js.addPair(AFldName,'NULL')
end;
end;
result := js.ToString;
finally
js.Free;
AContext.Free;
end;
end;
end.