forked from hgourvest/superobject
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuJsonSerializer.pas
103 lines (85 loc) · 2.18 KB
/
uJsonSerializer.pas
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
unit uJsonSerializer;
interface
uses sysutils, classes, generics.collections;
// ÷òîáû ðàáîòàòü ñ àòðèáóòàìè, íóæíî â ìîäóëå, ãäå îïèñûâàåòñÿ ìîäåëü äîáàâèòü â uses superobject
// þçàòü òàê:
// [SOName('jsonfieldname')]]
type
TJsonSerializer = class
public
class function Serialize<T>(const obj: T): String;
class function Deserialize<T>(const Json: string): T;
end;
TClassCloner = class
class function Clone(aValue: TObject): TObject; overload;
class function Clone<T: class>(aValue: TObject): T; overload;
end;
TXMLSerializer = class
public
class function Deserialize<T>(const XML: string): T;
end;
implementation
uses superobject, dbxjsonreflect, Json, rtti, typinfo, controls, superxmlparser;
{ TJsonSerializer }
class function TJsonSerializer.Deserialize<T>(const Json: string): T;
var
ctx: TSuperRttiContext;
begin
ctx := TSuperRttiContext.Create;
try
result := ctx.AsType<T>(SO(Json));
finally
freeandnil(ctx);
end;
end;
class function TJsonSerializer.Serialize<T>(const obj: T): String;
var
ctx: TSuperRttiContext;
begin
ctx := TSuperRttiContext.Create;
try
result := ctx.AsJson(obj).AsJson(true, false);
finally
freeandnil(ctx);
end;
end;
{ TClassCloner }
class function TClassCloner.Clone(aValue: TObject): TObject;
var
MarshalObj: TJSONMarshal;
UnMarshalObj: TJSONUnMarshal;
JSONValue: TJSONValue;
begin
result := nil;
MarshalObj := TJSONMarshal.Create;
UnMarshalObj := TJSONUnMarshal.Create;
try
JSONValue := MarshalObj.Marshal(aValue);
try
if Assigned(JSONValue) then
result := UnMarshalObj.Unmarshal(JSONValue);
finally
JSONValue.Free;
end;
finally
MarshalObj.Free;
UnMarshalObj.Free;
end;
end;
class function TClassCloner.Clone<T>(aValue: TObject): T;
begin
result := Clone(aValue) as T;
end;
{ TXMlDeserializer }
class function TXMLSerializer.Deserialize<T>(const XML: string): T;
var
ctx: TSuperRttiContext;
begin
ctx := TSuperRttiContext.Create;
try
result := ctx.AsType<T>(XMLParseString(XML, true));
finally
freeandnil(ctx);
end;
end;
end.