macrolen 给了这样一些数据, 说是用淘宝的 API 获取的 JSON 数据, 让我帮助解析:


把这些数据保存在: c:\temp\json.txt; 然后在窗体上放一个 Memo 和四个 Button ...
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses SuperObject;
var jo: ISuperObject;

//载入并建立对象
procedure TForm1.FormCreate(Sender: TObject);
const
  JsonPath = 'c:\temp\json.txt';
begin
  Assert(FileExists(JsonPath), '文件不存在');
  with TStringList.Create do
  begin
    LoadFromFile('c:\temp\json.txt');
    jo := SO(Text);
    Free;
  end;
end;

//按格式查看所有
procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Text := jo.AsJSon(True, False);
end;

//查看: items_search_response.item_search.item_categories
procedure TForm1.Button2Click(Sender: TObject);
begin
  Memo1.Text := jo['items_search_response.item_search.item_categories'].AsJSon(True, False);
end;

//查看: items_search_response.item_search.items
procedure TForm1.Button3Click(Sender: TObject);
begin
  Memo1.Text := jo['items_search_response.item_search.items'].AsJSon(True, False);
end;

//遍历 items_search_response.item_search.items.item 数组中的指定元素
procedure TForm1.Button4Click(Sender: TObject);
var
  ja: TSuperArray;
  i: Integer;
begin
  ja := jo['items_search_response.item_search.items.item'].AsArray;
  Memo1.Clear;
  for i := 0 to ja.Length - 1 do
  begin
    Memo1.Lines.Add(ja.O[i].Format('%cid%; %location.state%; %location.city%'));
  end;
end;

end.


另外 SuperObject 当前的最新版本是: SuperObjectv1.2.3, 还没有测试它新增的功能, 不过我这个是用它做的.

posted on 2010-01-18 18:18  万一  阅读(13601)  评论(16编辑  收藏  举报