kbmmw 中JSON 操作入门

现在各种系统中JSON 用的越来越多。delphi 也自身支持JSON 处理。

今天简要说一下kbmmw 内部如何使用和操作JSON。

kbmmw 中json的操作是以TkbmMWJSONStreamer 为基础,要导入、导出JSON字符串, 首先要创建TkbmMWJSONStreamer.

 然后是 TkbmMWJSONObject和 TkbmMWJSONArray。

先举一个最简单的例子。

procedure TForm1.Button3Click(Sender: TObject);
var
  myjson:TkbmMWJSONStreamer;
  alljson: TkbmMWJSONObject;
  s:String;
begin

   myjson:=TkbmMWJSONStreamer.Create; // 建立JSON流

   alljson:=TkbmMWJSONObject.Create; // 建立JSON 对象

   alljson.AsString['root']:='ok'; // 赋值

   s:=myjson.SaveToUTF16String(alljson);
   memo1.Lines.Clear;
   memo1.Lines.Add(s);

   alljson.Free;
   myjson.Free;
end;

以上代码运行结果为

{"root":"ok"}

继续修改添加一些代码

procedure TForm1.Button3Click(Sender: TObject);
var
  myjson:TkbmMWJSONStreamer;
  alljson: TkbmMWJSONObject;
  djson:TkbmMWJSONObject;
  s:String;
begin

   myjson:=TkbmMWJSONStreamer.Create;

   alljson:=TkbmMWJSONObject.Create;

   djson:=TkbmMWJSONObject.Create; // 新建一个子对象

   djson.Asinteger['ID']:=1;
   djson.AsString['name']:='xalion';
   djson.AsDateTime['date']:=now;

   alljson.AsObject['result']:=djson;

   s:=myjson.SaveToUTF16String(alljson);
   memo1.Lines.Clear;
   memo1.Lines.Add(s);


   alljson.Free;
   myjson.Free;

end;

 

这样返回的结果如下

{"result":{"ID":1,"name":"xalion","date":"2017-07-01T01:00:00.427+08:00"}}

即返回一条记录信息。

如果需要返回多条记录,就需要使用TkbmMWJSONArray。

procedure TForm1.Button3Click(Sender: TObject);
var
  myjson:TkbmMWJSONStreamer;
  alljson: TkbmMWJSONObject;
  djson:TkbmMWJSONObject;
   datajson: TkbmMWJSONArray;
  s:String;
  I: Integer;
begin

   myjson:=TkbmMWJSONStreamer.Create;  // 建立一个JSON 流

   alljson:=TkbmMWJSONObject.Create;  // 建立一个JOSN 根对象

   datajson:=TkbmMWJSONArray.Create;   //建立一个JSON 数组

   for I :=1 to 10 do
    begin
         djson:=TkbmMWJSONObject.Create;
         djson.Asinteger['ID']:=i;
         djson.AsString['name']:='xalion';
         djson.AsDateTime['date']:=now;

         datajson.Add(djson);         // 加入数据

    end;

    alljson.AsArray['result']:=datajson;

   s:=myjson.SaveToUTF16String(alljson);
   memo1.Lines.Clear;
   memo1.Lines.Add(s);


   alljson.Free;
   myjson.Free;

end;

最后输出结果为

{"result":[{"ID":1,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":2,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":3,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":4,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":5,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":6,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":7,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":8,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":9,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"},{"ID":10,"name":"xalion","date":"2017-07-01T01:16:44.960+08:00"}]}

下面讲一下如何访问JSON字符串里面的对象和值

procedure TForm1.Button4Click(Sender: TObject);
var
  myjson:TkbmMWJSONStreamer;
  alljson: TkbmMWJSONObject;
begin
    myjson:=TkbmMWJSONStreamer.Create;  // 建立一个JSON 流

    alljson:=TkbmMWJSONObject( myjson.LoadFromUTF16String(memo1.Lines.Text)); // 载入到根JSON

    memo2.Lines.Clear;

    memo2.Lines.Add(alljson.AsString['root']);

    alljson.Free;
    myjson.Free;

end;

运行截图

访问对象

procedure TForm1.Button4Click(Sender: TObject);
var
  myjson:TkbmMWJSONStreamer;
  alljson: TkbmMWJSONObject;
begin
    myjson:=TkbmMWJSONStreamer.Create;  // 建立一个JSON 流

    alljson:=TkbmMWJSONObject( myjson.LoadFromUTF16String(memo1.Lines.Text)); // 载入到根JSON

    memo2.Lines.Clear;

    memo2.Lines.Add(alljson.AsObject['result'].AsString['name'] );

    alljson.Free;
    myjson.Free;

end;

运行结果

访问数组

procedure TForm1.Button4Click(Sender: TObject);
var
  myjson:TkbmMWJSONStreamer;
  alljson: TkbmMWJSONObject;
   jresult:TkbmMWJSONArray;
begin
    myjson:=TkbmMWJSONStreamer.Create;  // 建立一个JSON 流

    alljson:=TkbmMWJSONObject( myjson.LoadFromUTF16String(memo1.Lines.Text)); // 载入到根JSON

    memo2.Lines.Clear;

    jresult:=TkbmMWJSONArray(alljson.AsArray['result']);    // 返回数组


    memo2.Lines.Add(jresult.AsObject[5].AsString['name'] );


    alljson.Free;
    myjson.Free;

end;

运行结果

 

 延伸一下

procedure TForm1.Button4Click(Sender: TObject);
var
  myjson:TkbmMWJSONStreamer;
  alljson: TkbmMWJSONObject;
  jresult:TkbmMWJSONArray;
  i:integer;
begin
    myjson:=TkbmMWJSONStreamer.Create;  // 建立一个JSON 流

    alljson:=TkbmMWJSONObject( myjson.LoadFromUTF16String(memo1.Lines.Text)); // 载入到根JSON

    memo2.Lines.Clear;

    jresult:=TkbmMWJSONArray(alljson.AsArray['result']);    // 返回数组


    memo2.Lines.Add(jresult.AsObject[5].AsString['name'] );

    memo2.lines.Add('数组大小:'+jresult.Count.ToString  );
    memo2.lines.Add('属性个数:'+jresult.AsObject[5].PropertyCount.ToString  );

    for I := 1 to jresult.AsObject[5].PropertyCount do

          memo2.lines.Add('属性'+i.ToString+'名:'+jresult.AsObject[5].PropertyName[i-1]);


    alljson.Free;
    myjson.Free;

end;

运行结果

总之,用kbmmw 操作JSON 非常方便,更牛的是,这个可以与XML,BSON,YAML 实现无缝互转。

 

winxp+delphi7+kbmmw4.0.3+unidac+mssql2000+dbgrideh 基本实现xalion所说的功能并加上自己的一些编写经验 1、远程方法调用 2、取图像(流的使用) 3、查询数据 4、编辑数据:增、删、改(如果操作错误会进行相应的提示) 5、存储过程使用方法(存储过程参数自动创建) 6、动态创建数据集并执行Insert操作 7、命名查询(namedQuery) 8、事务操作(直接写SQL语句更新表的事务操作,有个重要的属性要设置,否则会更新不成功) 9、使用的数据库:sqlserver 2000,请到服务器的FDM单元把连接参数改下 10、数据库kbm_test结构参见:kbm_test.sql 11、安装kbmMw时请把配置文件 kbmMWConfig.inc {$DEFINE KBMMW_UNIDAC_SUPPORT} // UNIDAC support. 前面的//去掉 12、使用delphi7 2012年8月新增功能与说明 1、客户端断线重连:kbmMWTCPIPIndyClientTransport1.MaxRetries := 2;//重连一次 2、对象传输 3、JSON传输(利用kbmmw带的json库实现) 4、客户端断开代码: if FDM.kbmMWSimpleClient1.Transport.IsConnected then begin //memo1.Lines.Add('程序已有300秒没有进行操作,断开连接'); FDM.kbmMWSimpleClient1.Disconnect; end; 5、新增远程过程调用函数(直接SQL语句操作数据库): startTran:启动事务 commitTran:提交事务 rollbackTran:回滚事务 openSql:打开SQL语句 execSql:执行SQL语句 注openSql、execSql两个函数体代码使用对象连接池技术,无对象创建与释放,以提高系统效率, 具体能提高多少,未实测 6、增加HTTP协议例子(参考资料:kbmMW_and_AJAX.pdf),提供http-get的功能,http-post的功能可参照http-get方法实现 7、提供数据集转jsonjson转数据集 (CDSFromJSon(CDS:TClientDataSet;JsonStr:string):Boolean)单元:uDBJson.pas 参照代码可自行把jsonkbmmwQuery kbmmw编译unidac方法: 修改单元kbmMWUNIDAC.pas,本人在数据库很少用到blob字段,所以在代码里屏蔽掉blob字段的处理, 经测试数据库表字段类型为Text时,程序可以正常处理 报OLE DB error occured. CoInitialize has not been called (server)错误解决: unidac41src\Source\UniProviders\SQLServer\OLEDBAccessUni.pas constructor TOLEDBConnection.Create; begin inherited; CoInitialize(nil);//加此句 FCommand := nil; ... end; destructor TOLEDBConnection.Destroy; begin Disconnect; FCommand.Free; CoUninitialize;//加此句 inherited; end; 作者:chensm@vip.qq.com kbmmw开发交流群:209321818
RealThinClient SDK Copyright 2004-2013 (c) RealThinClient.com All rights reserved. -------------------------------- ******************************** 1.) License Agreement 2.) Install RTC SDK components in Delphi 3.) Make the RTC SDK accessible from XCode (for iOS development) 4.) Update RTC SDK components in Delphi 5.) Help 6.) Demos 7.) Support ******************************** -------------------------------- --------------------- 1.) License Agreement --------------------- Please read the RTC SDK License Agreement before using RTC SDK components. You will find the RTC SDK License Agreement in the "License.txt" file. -------------------------------- 2.) INSTALL RTC SDK components in Delphi -------------------------------- After you have unpacked the files in a folder of your choice and started Delphi, open the "Package_Main" Project Group where you will find 3 packages: rtcSDK.dpk -> The main Package. Includes all Client and Server HTTP/S components. rtcSDK_DBA.dpk -> Optional, includes only "TRtcMemDataSet" and "TRtcDataSetMonitor" components. rtcSDK_RAW.dpk -> Optional, includes only raw TCP/IP and UDP communication components. Install the components in Delphi by using the "Install" button, or the "Install" menu option. In older Delphi versions, you will see the "Install" button in the Project Manager window. In newer Delphi versions, you will find the "Install" option if you right-click the package file in the Project Manager accessed in the "View" drop-down menu. When compiled and installed, you will see a message listing all components installed. After that, you should add the path to the RTC SDK's "Lib" folder to "Library paths" in Delphi. In older Delphi versions, the Library Path is located in the "Tools / Environment Options" menu. Select the "Library" tab and add the full path to the RTC SDK's "Lib" folder to "Library path". In newer Delphi versions, Library Paths are located in the "Tools / Options" menu. Select the "Environment Options / Delphi Options / Library" tree branch, where you will find the "Library Path" field. There, you should click the "..." button next to "Library path" and add the path to the RTC SDK's "Lib" folder. In Delphi XE2 and later, you will also see a "Selected Platform" drop-down menu. There, all the settings are separated by platforms, so you will need to repeat the process for every platform you want to use the "RTC SDK" with. ------------------------------- 3.) Make the RTC SDK accessible from XCode (for iOS development) - Delphi XE2 ------------------------------- For the FPC compiler to find RTC SDK files, you can either copy the complete "Lib" folder (with sub-folders) from the RTC SDK package into the "/Developer/Embarcadero/fmi" folder (quick and dirty solution), or ... You can add the path to the RTC SDK 揕ib?folder (located on your Windows PC, made accessible to Mac over LAN) to the FPC search path. Unfortunatelly, there is no 損arameter?for adding FPC search paths in XCode directly, so you will need to do this manually for every XCode Project. And not only once, but every time you recreate XCode Project files by using the 揹pr2xcode?tool, because all your changes will be overwritten by "dpr2xcode". To avoid having to make these changes too often, use "dpr2xcode" ONLY if you have made changes to the Project file itself (changed the Project icon, for example). There is no need to recreate XCode Project files if you have only changed forms or units inside the Project. To add the RTC SDK paths to FPC, you will need to modify the file "xcode/<ProjectName>.xcodeproj/project.pbxproj". The path to the RTC SDK 揕ib?folder needs to be added as two new ?Fu?parameters. Once for iOS-Simulator and once for iOS-Device compilation, both of are configured through the 搒hellScript?parameter. The best place to add the RTC SDK Lib path is after the FireMonkey path, so you should search for ?Fu/Developer/Embarcadero/fmi?in the above mentioned XCode Project file. You will find 2 such instances in the "ShellScript" line and you should add the path to the RTC SDK Lib folder directly after each "-Fu/Developer/Embarcadero/fmi" instance. For example, if you have made the complete RTC SDK folder on your Windows PC available to your Mac OSX through a network share named 揜TC_SDK?(read/write access rights to that folder will be required for FPC compilation to work), you should add ?Fu/Volumes/RTC_SDK/Lib?after both ?Fu/Developer/Embarcaedro/fmi?locations. One is for the iOS-Simulator, the other one for the iOS device. That will be enough to let FPC know where to look for RTC SDK files. Should you still get "File not found" errors when trying to compile a Project using RTC files, make sure the path you have used is correct and that Mac OSX has read and write access to that folder. PS. Before configuring access to the RTC SDK, you will need to have OSX 10.6 or 10.7, the latest XCode 4.x version and both packages provided by Embarcadero (included with RAD Studio XE2) installed on your Mac. To make sure your Mac OSX configuration is correct, create an empty "FireMonkey iOS HD" Project, use "dpr2xcode" to create XCode Project files and try to run that Project from XCode, either inside the iOS-Simulator or directly on your iOS device (iPhone or iPad). ------------------------------- 4.) UPDATE RTC SDK components in Delphi ------------------------------- Download the latest version of the RTC SDK from the RTC Support Forum: http://sf.realthinclient.com Information about recent RTC SDK updates is in the "Updates*.txt" file(s). To update RTC SDK components, it's adviseable to uninstall the old packages and delete the old BPL and DCP files (rtcSDK.bpl, rtcSDK.dcp, rtcSDK_DBA.bpl, rtcSDK_DBA.dcp, rtcSDK_RAW.bpl and rtcSDK_RAW.dcp) before installing new packages. To uninstall RTC SDK components, after you start Delphi, open the menu "Component / Install Packages ..." where you will see a list of all packages currently installed in your Delphi. Scroll down to find "RealThinClient SDK" and click on it (single click). When you select it, click the button "Remove" and Delphi will ask you if you want to remove this package. Clicking "Yes" will uninstall the RTC SDK. After that, *close* Delphi and follow step (2) to install the new RTC SDK package. NOTE: Uninstalling the RTC SDK package will also uninstall all packages which are using the RTC SDK (for example, rtcSDK_DBA, rtcSDK_RAW and "Nexus Portal" packages). So ... if you are using "Nexus Portal" or any other product using the RTC SDK, you will need to Build and Install all related packages again, after you reinstall the RTC SDK. ------------- 5.) Help ------------- The best place to start learning about RTC SDK is the QuickStart guide. After going through the online lessons, you should also go through the QuickStart examples included in the RTC SDK package. When you are done examining QuickStart examples, I suggest browsing through the FAQ. Even if you won't be reading all the articles, you should at least get the feeling about the information included there. RTC SDK Demos are another good source of information, including a lot of examples and best practices for using the RealThinClient SDK. And the most extensive source of information on the RealThinClient SDK are Help files. Some of the information is spread across the files, but if you know which class you need, you will most likely be able to find what you are looking for. When you start working on your project, the FAQ will come in handy when you have to do something specific (use Sessions, accept form post data, write and call remote functions, etc). The FAQ is continually being extended, as more questions come in. If you have a question for which you were unable to find the answer in the QuickStart guide, QuickStart examples or the FAQ ?and searching through the Help files didn't give you the answers you need, don't hesitate to post your question(s) on Developer Support groups. The latest Help file for Off-line viewing is in the "Help" folder: - "Help\RTCSDK_Help.chm" ------------------- 6.) Demos ------------------- You can find Demos using RTC SDK components in the "Demos" folder. Simple Quick Start Examples are available in the "QuickStart" folder. There are also 5 Project Groups which include all the Demos and Quick Start examples: * Demos_VCL - Demos using the VCL and the rtcSDK.dpk * Demos_VCL_DBA - Demos using the VCL with the rtcSDK.dpk and rtcSDK_DBA.dpk * Demos_FMX - Demos using FMX (Win,OSX,iOS) with the rtcSDK.dpk * Demos_FMX_DBA - Demos using FMX (Win,OSX,iOS) with the rtcSDK.dpk and rtcSDK_DBA.dpk * Examples_QuickStart_VCL - Short "QuickStart" examples using the VCL with the rtcSDK.dpk For short descriptions of available demos and quick start examples, please find the "Readme_Demos.txt" file in the "Demos" folder, and "Readme_QuickStart.txt" file in the QuickStart folder. ------------- 7.) Support ------------- More information on RTC SDK: > http://www.realthinclient.com/about.htm Download the latest version of RTC components and get Support through the RTC Forums: > http://sf.realthinclient.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值