一直盼着 Delphi 能够直接支持 "正则表达式" 与 "JSON";
Delphi 2009 刚来的时候, 有了 JSON, 但不好, 那时尝试过一点. 这是以前的链接: 什么是 JSON?
Delphi 2010 带了两个相关单元: DBXJSON、DBXJSONReflect 貌似很强大, 但主要是给 DataSnap 准备的; 尝试了半天, 也很失望: 可能给 DataSnap 网络数据传递够用了, 但太简陋了, 好像是没写完, 对中文支持也有问题.
我想不等了, 找第三方吧, 真的找到了惊喜: JSON �C SuperObject v1.1(简介、下载), Henri Gourvest 的大作!
里面还有 XML 相关的一个单元, 慢慢看吧.
unit Unit1; interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); end; var Form1: TForm1; implementation{$R *.dfm}uses SuperObject; //SuperObject 提倡使用接口; ParseString 是 TSuperObject 类的 Class 方法procedure TForm1.Button1Click(Sender: TObject); var jo: ISuperObject; begin jo := TSuperObject.ParseString('{"No1":"张三", "No2":"李四"}'); ShowMessage(jo['No1'].AsString); {张三}end; //有个共用函数 SO, 可方便实现接口procedure TForm1.Button2Click(Sender: TObject); var jo: ISuperObject; begin jo := SO('{"No1":"张三", "No2":"李四"}'); ShowMessage(jo['No2'].AsString); //李四end; end.
SuperObject 构建一个 JSON 的常用方法: 从字符串、从文件、从流.
unit Unit1; interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; 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; const JsonStr = '{"No1":"张三", "No2":"李四"}'; //从字符串构建procedure TForm1.Button1Click(Sender: TObject); var jo: ISuperObject; begin jo := SO(JsonStr); {或者用使用下面语句, SO 函数就是调用了 TSuperObject.ParseString}//jo := TSuperObject.ParseString(JsonStr); ShowMessage(jo.AsJSon(True, False)); end; //从文件构建procedure TForm1.Button2Click(Sender: TObject); const path = 'c:\temp\json.txt'; var jo: ISuperObject; begin{产生个测试文件; SuperObject 对中文支持也不太好, 读取它自己保存的文件吧} SO(JsonStr).SaveTo(path); {这就产生并保存了 json 文件} jo := TSuperObject.ParseFile(path); ShowMessage(jo.AsJSon(True, False)); end; //从流构建procedure TForm1.Button3Click(Sender: TObject); var jo: ISuperObject; stm: TStream; b: Byte; begin{模拟个测试流; 看看它能接受的编码够原始的, 它存取文件也是如此} stm := TStringStream.Create('{"No2":"\u674e\u56db","No1":"\u5f20\u4e09"}'); jo := TSuperObject.ParseStream(stm); ShowMessage(jo.AsJSon(True, False)); stm.Free; end; //AsJSon 的参数procedure TForm1.Button4Click(Sender: TObject); var jo: ISuperObject; begin jo := SO(JsonStr); ShowMessage(jo.AsJSon); ShowMessage(jo.AsJSon(True)); ShowMessage(jo.AsJSon(True, False)); ShowMessage(jo.AsJSon(False, False)); end; end.更多内容:http://www.cnblogs.com/del/category/215158.html