Delphi中使用ISuperObject解析Json数据的实现代码

Java、Php等语言中都有成熟的框架来解析Json数据,可以让我们使用很少的代码就把格式化好的json数据转换成程序可识别的对象或者属性,同时delphi中也有这样的组件来实现此功能,即IsuperObject。如果还没有这个组件的请在网上搜索下载或者在下面留言处留下你的邮箱向本人索取。

下面先说一下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.
作者:mdxy-dxy

%s 个评论

要回复文章请先登录注册