zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    sublime text3中html的使用
    WEB如何入门?各种渗透攻击如何入门?
    考思科认证NA过程的学习笔记
    HTML URL 编码(学习笔记)
    学习HTML过程中的笔记
    必学
    playfair密码
    二三级计算机考试时间
    DAY 135 VUE
    DAY 134 RBAC
  • 原文地址:https://www.cnblogs.com/cinemaparadiso/p/12082053.html
Copyright © 2011-2022 走看看