Delphi中使用ISuperObject解析Json数据

2023-01-03 14:33:21 作者:admin

本文整理自网络,侵删。

 下面先说一下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 stringgrid1读取加载excel文件

Delphi tlistview控件里添加背景色

Delphi mediaplayer android 下播放 mp4 的问题

Delphi 替换其他程序里面的函数为自己的函数

Delphi检测鼠标指针的改变(全局)

Delphi里实现文件格式关联应用程序的功能

Delphixe ansi字符串utf-8编码判断

Delphi 使用钩子函数 - 数据传递

Delphi 修改内存

Delphi android 拨打电话

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



在线咨询 拨打电话