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;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Buttons, superobject;type TFmMain = class(TForm) : TLabel; procedure BitBtn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end;var FmMain: TFmMain;implementation{$R *.dfm}procedure TFmMain.Bit Btnet( 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'] <> 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.一個簡單的Delphi使用ISuperObject解析json的例子:Delphi_Json_jb51.rar