JSON 之 SuperObject(10): Merge、Clone、ForcePath



unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls;



type

  TForm1 = class(TForm)

    Button1: TButton;

    Button2: TButton;

    Button3: TButton;

    procedure Button1Click(Sender: TObject);

    procedure Button2Click(Sender: TObject);

    procedure Button3Click(Sender: TObject);

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



uses SuperObject;



//Merge 合并

procedure TForm1.Button1Click(Sender: TObject);

var

  jo,jt: ISuperObject;

begin

  jo := SO('{X:1}');

  jt := SO('{Y:2}');

  jo.Merge(jt);

  ShowMessage(jo.AsJSon);  // {"Y":2,"X":1}

//

  jo := SO('{X:1, Y:2}');

  jt := SO('{Y:3}');

  jo.Merge(jt);

  ShowMessage(jo.AsJSon);  // {"Y":3,"X":1}

//

  jo := SO('{X:1, Y:2}');

  jt := SO('{Y:[5,6,7]}');

  jo.Merge(jt);

  ShowMessage(jo.AsJSon);  // {"Y":[5,6,7],"X":1}

//

  jo := SO('{A:{x:1, y:2}}');

  jt := SO('{A:{m:3, n:4}}');

  jo.Merge(jt, True);

  ShowMessage(jo.AsJSon);  // {"A":{"y":2,"x":1,"n":4,"m":3}}

end;



//Clone 克隆

procedure TForm1.Button2Click(Sender: TObject);

var

  jo,jt: ISuperObject;

begin

  jo := SO('{A:{x:1, y:2, z:3}}');

  jt := jo.Clone;



  jt.I['A.x'] := 7;

  jt.I['A.y'] := 8;

  jt.I['A.z'] := 9;



  ShowMessage(jo.AsJSon); // {"A":{"z":3,"y":2,"x":1}}

  ShowMessage(jt.AsJSon); // {"A":{"z":9,"y":8,"x":7}}



  //如果不是克隆

  jo := SO('{A:{x:1, y:2, z:3}}');

  jt := jo;



  jt.Delete('A.x');

  jt.Delete('A.y');



  ShowMessage(jo.AsJSon); // {"A":{"z":3}}

  ShowMessage(jt.AsJSon); // {"A":{"z":3}}

end;



//ForcePath 指向子对象

procedure TForm1.Button3Click(Sender: TObject);

var

  jo,jt,ja: ISuperObject;

begin

  jo := SO('{A:{x:1,y:2}, B:[]}');



  {通过 ForcePath 可指向一个子对象; 当子对象修改时, 原对象当然也会修改, 本来就是同一个}

  jt := jo.ForcePath('A');

  jt.I['x'] := 9;

  ShowMessage(jo.AsJSon); // {"B":[],"A":{"y":2,"x":9}}



  {原对象修改, 当然子对象也会修改}

  ja := jo.ForcePath('B', stArray);

  jo.A['B'][0] := SO('m');

  jo.A['B'][1] := SO('n');

  ShowMessage(ja.AsJSon); // ["m","n"]





  {ISuperObject.ForcePath 和 ISuperObject.O[] 差不多, 只是后者是可读写的}

  jo := SO('{A:{x:1,y:2}, B:[]}');

  jt := jo.O['A']; //或简写为: jt := jo['A'];

  jt.I['x'] := 8;

  ShowMessage(jo.AsJSon); // {"B":[],"A":{"y":2,"x":8}}

end;



end.


 
   

你可能感兴趣的:(object)