JSON与Delphi Object的互换
Delphi自从增强了RTTI后,语言的可灵活性多大增强,Delphi的dbExpress中提供了DBXJSON,和DBXJSONReflect两个单元,可提供JSON序列化
下面的例子是实现Delphi实体对象转换为JSON字符串,以及JSON字符串转换为Delphi 实体对象的示例:(在Delphi XE3测试通过)
1 unit Unit2; 2 3 interface 4 5 uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, 6 DBXJSON, DBXJSONReflect; 7 8 type 9 TPerson = class(TObject) 10 public 11 Name: String; 12 Password: String; 13 Age: Integer; 14 end; 15 16 TForm2 = class(TForm) 17 Memo1: TMemo; 18 procedure FormCreate(Sender: TObject); 19 private 20 function ObjectToJSON(AData: TObject): TJSONValue; 21 function JSONToObject(AJSONValue: TJSONValue): TObject; 22 public 23 end; 24 25 var 26 Form2: TForm2; 27 28 implementation 29 30 {$R *.dfm} 31 32 function TForm2.JSONToObject(AJSONValue: TJSONValue): TObject; 33 var 34 lUnMarshal: TJSONUnMarshal; 35 begin 36 lUnMarshal := TJSONUnMarshal.Create(); 37 try 38 Result := lUnMarshal.Unmarshal(AJSONValue); 39 finally 40 FreeAndNil(lUnMarshal); 41 end; 42 end; 43 44 function TForm2.ObjectToJSON(AData: TObject): TJSONValue; 45 var 46 lMarshal: TJSONMarshal; 47 begin 48 lMarshal := TJSONMarshal.Create(); 49 try 50 Result := lMarshal.Marshal(AData); 51 finally 52 FreeAndNil(lMarshal); 53 end; 54 end; 55 56 procedure TForm2.FormCreate(Sender: TObject); 57 var 58 lPerson: TPerson; 59 lJSONValue: TJSONValue; 60 const 61 lJSONString: String = '{"type":"Unit2.TPerson","id":1,"fields":{"Name":"Hezihang","Password":"123","Age":23}}'; 62 begin 63 Memo1.Lines.Clear; 64 /// Object Convert to JSON 65 Memo1.Lines.Add('Object to JSON String'); 66 Memo1.Lines.Add('--------------------------------------'); 67 Memo1.Lines.Add(''); 68 lPerson := TPerson.Create; 69 lPerson.Name := 'Hezihang'; 70 lPerson.Password := '123'; 71 lPerson.Age := 23; 72 lJSONValue := ObjectToJSON(lPerson); 73 FreeAndNil(lPerson); 74 Memo1.Lines.Add(lJSONValue.ToString); 75 lJSONValue.Free; 76 Memo1.Lines.Add(''); 77 Memo1.Lines.Add('--------------------------------------'); 78 /// JSON Convert to Object 79 Memo1.Lines.Add(''); 80 Memo1.Lines.Add('JSON String'' To a Class Instance'''); 81 Memo1.Lines.Add('--------------------------------------'); 82 Memo1.Lines.Add(''); 83 lJSONValue := TJSONObject.ParseJSONValue(lJSONString); 84 lPerson := JSONToObject(lJSONValue) as TPerson; 85 lJSONValue.Free; 86 Memo1.Lines.Add('Name: ' + lPerson.Name); 87 Memo1.Lines.Add('Password: ' + lPerson.Password); 88 Memo1.Lines.Add('Age: ' + IntToStr(lPerson.Age)); 89 lPerson.Free; 90 Memo1.Lines.Add(''); 91 Memo1.Lines.Add('--------------------------------------'); 92 end; 93 94 end.