当前位置:学Delphi网文档资料专题讲解JSON

JSON学习---合并Merge,克隆Clone,指向子对象ForcePath

减小字体 增大字体 作者:万一  来源:万一的博客  发布时间:2010-10-15 23:30:27

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.

Tags:Merge Clone ForcePath

作者:万一
  • 好的评价 如果您觉得此文章好,就请您
      0%(0)
  • 差的评价 如果您觉得此文章差,就请您
      0%(0)

文章评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论