Delphi中使用ISuperObject解析Json数据


本文整理自网络,侵删。

 
下面先说一下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 2009 之 tcategorypanelgroup[5]: headerstyle

Delphi ioutils tdirectory获取一个目录下所有文件名,包括子目录

Delphi 打开android应用信息

Delphi 获取ie中选项卡标题

Delphi实现抓屏压缩并保存桌面图片

Delphi 动态调用chm文件

Delphi中实现控件的拖拽

Delphi shellexecute 发送邮件

Delphi调用命令行命令并获取返回信息

Delphi 服务器群集解决方案

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...