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 ZooShaiVCL_JSON;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DBXJSON, Data.DBXJSONReflect;
type
TZooShaiVCLJSONForm = class(TForm)
btnObjectToJSON: TButton;
Memo: TMemo;
procedure btnObjectToJSONClick(Sender: TObject);
public
type
TRtt = (trUn, trDeux, trTrois);
TTest = class(TPersistent)
private
Frtt: Trtt;
published
property Rtt: Trtt read Frtt write Frtt;
end;
end;
var
ZooShaiVCLJSONForm: TZooShaiVCLJSONForm;
implementation
{$R *.dfm}
type
TSLTJSONConverter = class(TJSONUnMarshal)
public
class function JsonStringToObject<T: class>(AJson: string): T;
class function ObjectToJsonString(AObject: TObject): string;
end;
procedure TZooShaiVCLJSONForm.btnObjectToJSONClick(Sender: TObject);
var
Test: TTest;
S: string;
begin
Test := TTest.Create;
Test.Rtt := Trtt.trDeux;
S := TSLTJSONConverter.ObjectToJsonString(Test);
Test.Free;
Memo.Lines.Add(S);
Test := TSLTJSONConverter.JsonStringToObject<TTest>(S);
Memo.Lines.Add(IntToStr(Ord(Test.Rtt)));
Test.Free;
end;
class function TSLTJSONConverter.JsonStringToObject<T>(AJson: string): T;
var
LJSONValue: Data.DBXJSON.TJsonValue;
LJSONObject: Data.DBXJSON.TJSOnObject;
LUnMarshaler: TSLTJSONConverter;
begin
LJSONValue := Data.DBXJSON.TJSOnObject.ParseJSONValue(AJson);
try
if assigned(LJSONValue) and (LJSONValue is TJSOnObject) then
LJSONObject := LJSONValue as TJSOnObject
else
Abort;
LUnMarshaler := TSLTJSONConverter.Create;
try
Result := LUnMarshaler.CreateObject(LJSONObject) as T;
finally
FreeAndNil(LUnMarshaler);
end;
finally
FreeAndNil(LJSONObject);
end;
end;
class function TSLTJSONConverter.ObjectToJsonString(AObject: TObject): string;
var
LMarshaler: Data.DBXJSONReflect.TJSONMarshal;
LJSONObject: TJSOnObject;
begin
LMarshaler := Data.DBXJSONReflect.TJSONMarshal.Create(TJSONConverter.Create);
try
LJSONObject := LMarshaler.Marshal(AObject) as TJSOnObject;
try
Result := LJSONObject.ToString;
finally
FreeAndNil(LJSONObject);
end;
finally
FreeAndNil(LMarshaler);
end;
end;
end. |
Partager