SuperObject 構建一個 JSON 的常用方法: 從字符串、從文件、從流.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses SuperObject;
const JSonStr = '{"No1":"張三", "No2":"李四"}';
//從字符串構建
procedure TForm1.Button1Click(Sender: TObject);
var
jo: ISuperObject;
begin
jo := SO(JSonStr);
{或者用使用下面語句, SO 函數就是調用了 TSuperObject.ParseString}
//jo := TSuperObject.ParseString(JSonStr);
ShowMessage(jo.AsJSon(True, False));
end;
//從文件構建
procedure TForm1.Button2Click(Sender: TObject);
const
path = 'c:\temp\JSon.txt';
var
jo: ISuperObject;
begin
{產生個測試文件; SuperObject 對中文支持也不太好, 讀取它自己保存的文件吧}
SO(JsonStr).SaveTo(path); {這就產生並保存了 JSon 文件}
jo := TSuperObject.ParseFile(path);
ShowMessage(jo.AsJSon(True, False));
end;
//從流構建
procedure TForm1.Button3Click(Sender: TObject);
var
jo: ISuperObject;
stm: TStream;
b: Byte;
begin
{模擬個測試流; 看看它能接受的編碼夠原始的, 它存取文件也是如此}
stm := TStringStream.Create('{"No2":"\u674e\u56db","No1":"\u5f20\u4e09"}');
jo := TSuperObject.ParseStream(stm);
ShowMessage(jo.AsJSon(True, False));
stm.Free;
end;
//AsJSon 的參數
procedure TForm1.Button4Click(Sender: TObject);
var
jo: ISuperObject;
begin
jo := SO(JSonStr);
ShowMessage(jo.AsJSon);
ShowMessage(jo.AsJSon(True));
ShowMessage(jo.AsJSon(True, False));
ShowMessage(jo.AsJSon(False, False));
end;
end.