本文整理自网络,侵删。
下面先说一下ISuperObject中几个常用的函数
function SO(const s: SOString = ‘{}’): ISuperObject; overload; 此函数传入json数据字符串,并返回一个ISuperObject对象,这一般是我们解析json时使用的第一个函数,如jObj := SO(jsonstr)。property O[const path: SOString]: ISuperObject read GetO write PutO; default; 如:jobj.O[‘username’],此函数被一个ISuperObject对象调用,方括号内的字符串为json中的字段名称,返回一个ISuperObject对象。property S[const path: SOString]: SOString read GetS write PutS; 此函数被一个ISuperObject对象调用,和O[‘username’]不同的是,它返回的是一个SoString,即一个字符串,使用方法 str := jObj.S[‘username’]; 同理的还有其他几个类似的函数,如I[‘age’]返回整数,B[‘isenable’]返回布尔型,A[‘users’]返回一个TSuperArray数组AsString, AsBoolean, AsInteger,AsArray,ISuperObject的函数,用来把ISuperObject转换成相应的数据类型。 下面我们看一个演示代码,json数据如下
{ "retcode": "1", "datafrom": "server", "users": "[{\"id\":1, \"username\": \"liuderu\", \"website\": \"bcoder.com\"},{\"id\":2, \"username\": \"Jeoe\", \"website\": \"baidu.com\"}]"}
Delphi版本2010,代码如下:
unit uFmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, Buttons, superobject;
type
TFmMain = class(TForm)
Memo1: TMemo;
ListView1: TListView;
BitBtn1: TBitBtn;
Label1: TLabel;
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FmMain: TFmMain;
implementation
{$R *.dfm}
procedure TFmMain.BitBtn1Click(Sender: TObject);
var
jRet, jUsers: ISuperObject;
aryUsers: TSuperArray;
retCode: integer;
strUsers: string;
i: integer;
begin
jRet := SO(Memo1.Text);
if (jRet.O['retcode'] <> nil) then begin
retCode := jRet.O['retcode'].AsInteger;
Label1.Caption := '返回值:' + IntToStr(retCode) + '; 数据来源:' + jRet.O['datafrom'].AsString;
if(jRet.O['retcode'].AsInteger = 1) then begin
strUsers := jRet.O['users'].AsString;
jUsers := SO(strUsers);
aryUsers := jUsers.AsArray;
for I := 0 to aryUsers.Length - 1 do begin
with ListView1.Items.Add do begin
Caption := aryUsers[i].O['id'].AsString;
SubItems.Add(aryUsers[i].O['username'].AsString);
SubItems.Add(aryUsers[i].O['website'].AsString);
end;
end;
end;
end;
end;
end.
http://bcoder.com/delphi/parse-json-data-in-delphi-by-using-isuperobject
相关阅读 >>
Delphi getsys32path()得到系统system32路径
Delphi firemonkey app 如何获得当前系统语言设置
Delphi shellexecute openurl 的跨平台实现
更多相关阅读请进入《Delphi》频道 >>