-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuJson.pas
More file actions
58 lines (48 loc) · 1.14 KB
/
Copy pathuJson.pas
File metadata and controls
58 lines (48 loc) · 1.14 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
unit uJson;
interface
uses
superobject, Windows, SysUtils, Rtti, TypInfo;
type
JsonSerializer<T> = class
public
class procedure FromJson(js: ISuperObject; var item: T); overload;
class procedure FromJson(jstr: string; var item: T); overload;
class function ToJson(item: T): ISuperObject;
end;
implementation
{ JsonSerializer<T> }
class procedure JsonSerializer<T>.FromJson(js: ISuperObject; var item: T);
var
v: TValue;
ctx: TSuperRttiContext;
begin
if js = nil then
raise Exception.Create('Invalid object');
ctx := TSuperRttiContext.Create;
try
TValue.Make(nil, TypeInfo(T), v);
ctx.FromJson(v.TypeInfo, js, v);
if v.TypeInfo.Kind = tkRecord then
v.Cast(v.TypeInfo).ExtractRawData(@item);
finally
ctx.Free;
end;
end;
class procedure JsonSerializer<T>.FromJson(jstr: string; var item: T);
begin
FromJson(SO(jstr), item);
end;
class function JsonSerializer<T>.ToJson(item: T): ISuperObject;
var
v: TValue;
ctx: TSuperRttiContext;
begin
ctx := TSuperRttiContext.Create;
try
TValue.Make(@item, TypeInfo(T), v);
Result := ctx.ToJson(v, SO);
finally
ctx.Free;
end;
end;
end.