-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxLogic.JSON.pas
More file actions
99 lines (80 loc) · 2.45 KB
/
MaxLogic.JSON.pas
File metadata and controls
99 lines (80 loc) · 2.45 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
Unit MaxLogic.JSON;
{ Version: 4.3
Description:
Small helpers for serialising and deserialising delphi objects.
Note, now simplified as the newer delphi (tested with Berlin) has already implemented most of the required stuff on its own.
so it is possible to have members of type TArray<T> or TObjectList<T>
where T is a class with a parameterless constructor and they will be serialized and deserialized by delphi quite well.
}
Interface
Uses
windows, classes, sysUtils, rest.JSON, rest.JSON.Types, rest.JsonReflect, system.JSON;
Type
TJSONSerializable = Class
Private
// JSONAttribute is in REST.Json.Types
// [JSONName('FirstName')]
// [JSONMarshalled(false)]
Public
Function ToJsonString: String;virtual;
Procedure SaveToJsonFile(Const FileName: String);
Class Function JsonToObject<T: Class, Constructor>(Const JSON: String): T; Static;
Class Function JsonFileToObject<T: Class, Constructor>(Const FileName: String): T; Static; static;
Class Function clone<T: Class, Constructor>(Const aInstance: TObject): T; Static;
End;
Function JsonObjectFromFile(Const FileName: String): TJsonObject;
Procedure JAdd(JsonObject: TJsonObject; aname: String; i: integer);
Implementation
Uses
ioUtils;
{ TJSONSerializable }
Function TJSONSerializable.ToJsonString: String;
Begin
result := TJson.ObjectToJsonString(self);
End;
Class Function TJSONSerializable.JsonToObject<T>(Const JSON: String): T;
Begin
result := REST.Json.TJson.JsonToObject<T>(JSON);
End;
class function TJSONSerializable.clone<T>(const aInstance: TObject): T;
var
jsonStr: String;
begin
jsonStr:= TJson.ObjectToJsonString(aInstance);
Result := JsonToObject<T>(jsonStr);
end;
Class
Function TJSONSerializable.JsonFileToObject<T>(Const FileName: String): T;
Var
s: String;
Begin
If fileExists(FileName) Then
Begin
s := TFile.ReadAllText(FileName);
result := JsonToObject<T>(s);
End
Else
result := T.create;
End;
Procedure TJSONSerializable.SaveToJsonFile(Const FileName: String);
Var
JSON: String;
Begin
JSON := self.ToJsonString;
TFile.WriteAllText(FileName, JSON, TEncoding.utf8);
End;
Function JsonObjectFromFile(Const FileName: String): TJsonObject;
Begin
result :=
TJsonObject.ParseJSONValue(
TFile.ReadAllText(FileName)
) As TJsonObject;
End;
Procedure JAdd(JsonObject: TJsonObject; aname: String; i: integer);
Var
jv: TJsonValue;
Begin
jv := TJSONNumber.create(i);
JsonObject.addPair(aname, jv);
End;
End.