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數據如下

  1. {
  2. "retcode": "1",
  3. "datafrom": "server",
  4. "users": "[{\"id\":1, \"username\": \"liuderu\", \"website\": \"bcoder.com\"},{\"id\":2, \"username\": \"Jeoe\", \"website\": \"baidu.com\"}]"
  5. }

Delphi版本2010,代碼如下:

  1. unit uFmMain;
  2.  
  3. interface
  4.  
  5. uses
  6. Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  7. Dialogs, StdCtrls, ComCtrls, Buttons, superobject;
  8.  
  9. type
  10. TFmMain = class(TForm)
  11. Memo1: TMemo;
  12. ListView1: TListView;
  13. BitBtn1: TBitBtn;
  14. Label1: TLabel;
  15. procedure BitBtn1Click(Sender: TObject);
  16. private
  17. { Private declarations }
  18. public
  19. { Public declarations }
  20. end;
  21.  
  22. var
  23. FmMain: TFmMain;
  24.  
  25. implementation
  26.  
  27. {$R *.dfm}
  28.  
  29. procedure TFmMain.BitBtn1Click(Sender: TObject);
  30. var
  31. jRet, jUsers: ISuperObject;
  32. aryUsers: TSuperArray;
  33. retCode: integer;
  34. strUsers: string;
  35. i: integer;
  36. begin
  37. jRet := SO(Memo1.Text);
  38. if (jRet.O['retcode'] <> nil) then begin
  39. retCode := jRet.O['retcode'].AsInteger;
  40. Label1.Caption := '返回值:' + IntToStr(retCode) + '; 數據來源:' + jRet.O['datafrom'].AsString;
  41.  
  42. ) then begin
  43. strUsers := jRet.O['users'].AsString;
  44. jUsers := SO(strUsers);
  45. aryUsers := jUsers.AsArray;
  46. do begin
  47. with ListView1.Items.Add do begin
  48. Caption := aryUsers[i].O['id'].AsString;
  49. SubItems.Add(aryUsers[i].O['username'].AsString);
  50. SubItems.Add(aryUsers[i].O['website'].AsString);
  51. end;
  52. end;
  53. end;
  54. end;
  55. end;
  56.  
  57. end.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM