1 Star 1 Fork 4

jinshaopu / dataset-serialize

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

原工程地址:https://github.com/viniciussanchez/dataset-serialize 由于使用的了高版本的类信息所以无法在Delphi7中无法使用,这里将其他修改为使用superobject来做JSON部分的处理

DataSet Serialize for Delphi

测试环境为Delphi7 DataSet Serialize is a set of features to make working with JSON and DataSet simple. It has features such as exporting or importing records into a DataSet, validate if JSON has all required attributes (previously entered in the DataSet), exporting or importing the structure of DataSet fields in JSON format. In addition to managing nested JSON through master detail or using TDataSetField (you choose the way that suits you best). All this using class helpers, which makes it even simpler and easier to use.

Prerequisites

  • [Optional] For ease I recommend using the Boss (Dependency Manager for Delphi) for installation, simply by running the command below on a terminal (Windows PowerShell for example):
boss install github.com/viniciussanchez/dataset-serialize

安装

添加Search Path Project > Options > Resource Compiler > Directories and Conditionals > Include file search path

../dataset-serialize/src
../dataset-serialize/src/core
../dataset-serialize/src/helpers
../dataset-serialize/src/providers
../dataset-serialize/src/types

开始使用

All features offered by DataSet Serialize are located in the class helper in unit DataSetSerializeHelper. To get your project started, simply add your reference where your functionality is needed. Here's an example:

uses DataSetSerializeHelper;

Let's now look at each feature, its rules and peculiarities, to deliver the best to all users.

DataSet to JSON

Creating a JSON object with information from a DataSet record seems like a very simple task for Delphi users. But that task just got easier. DataSet Serialize has two functions for this, namely ToJSONObject and ToJSONArray. Let's look at the use of the functions:

var
  LJSONArray: TsuperArray;
  LJSONObject: IsuperObject;  
begin
  LJSONObject := qrySamples.ToJSONObject(); // export a single record
  LJSONArray := qrySamples.ToJSONArray(); // export all records 
end;

What is the difference between the two functions? ToJSONObject will only convert the current DataSet record to a TJSONObject. ToJSONArray will convert to a TJSONArray all the records of the DataSet and not just the selected record.

Parameters

  • AChildRecords - Indicates whether or not to export child records (via master detail or TDataSetField).
  • AOnlyUpdatedRecords - Indicates whether to export only records that have been modified (records added, changed, or deleted). This feature is only available when using FireDAC. The CachedUpdates property must be True;

ToJSONObject

  • If the DataSet is empty or not assigned, a blank JSON object ({}) will be returned;
  • The field that does not have the visible (True) property will be ignored. The same is true if its value is null or empty;
  • The attribute name in JSON will always be the field name in lower case, even if the field name is in upper case;
  • If the field is of type TDataSetField, a nested JSON is generated (JSONObject if it is just a child record, or JSONArray if it is more than one). The most suitable way for this type of situation is to create a master detail;
  • All child records will be exported as a JSONArray;
  • When using the AOnlyUpdatedRecords parameter of the ToJSONObject or ToJSONArray method, the JSON item is added to an "object_state" property responsible for defining what happened to the record (deleted, included or changed);
  • When a JSON array is created to represent a nested JSON using Master Detail, the DataSet name will be the name of the generated JSON attribute. There is a rule where if the DataSet name starts with qry (query) or mt (memtable), these initials are ignored, leaving only the rest as the attribute name in JSON.

ToJSONArray

  • If the DataSet is empty or not assigned, a blank JSON array ([]) will be returned;
  • Follows the same rules as ToJSONObject;

Save and load structure

A not very useful but important feature is SaveStructure and LoadStructure. As the name already said, it is possible to save the entire structure of fields configured in the DataSet and also load a structure in JSON format. Here's an example of how to load and export DataSet fields:

var
  LJSONArray: TSuperArray;
begin
  LJSONArray := qrySamples.SaveStructure;
  qrySamples.LoadStructure(LJSONArray, True);
end;

The following properties are controlled:

Alignment, FieldName, DisplayLabel, DataType, Size, Key, Origin, Required, Visible, ReadOnly, and AutoGenerateValue;

Parameters

  • AOwns - Indicates who is responsible for destroying the passed JSON as a parameter.

SaveStructure

  • If the field count of DataSet equals zero, a blank JSON array ([]) will be returned;

LoadStructure

  • DataSet cannot be activated and Must not have fields defined;

Validate JSON

The ValidateJSON function is very useful when we want to validate on a server for example if the JSON we received in the request has all the required information. Practically, all fields in the DataSet are traversed, checking if the required fields were entered in JSON. If the field is required and has not been entered in JSON, it will be added to the JSON Array returned by the function. See the example below:

begin
  LJSONArray := qrySamples.ValidateJSON('{"country":"Brazil"}');
end;

Upon receiving {"country": "Brazil"}, assuming our DataSet has 3 fields (ID, NAME, COUNTRY), and the ID and NAME field are required, the following will be returned:

[{"field":"ID","error":"Id not informed"},{"field":"NAME","error":"Name not informed"}]

Parameters

  • ALang - Responsible for changing the language used in the assembly of messages (default is English);
  • AOwns - Indicates who is responsible for destroying the passed JSON as a parameter;

ValidateJSON

  • If JSON is not assigned or fields count equals zero an exception is raised.
  • The default language of messages is English;
  • Even if all required fields are entered, an empty JSON array ([]) is returned;
  • A required field must have its Required property equal to True.
  • The DisplayLabel property can be used to customize the message;

Load from JSON

DataSet Serializa allows you to load a DataSet with a JSONObject, JSONArray and even a nested JSON all summarized in one method: LoadFromJSON(). Here's an example of how to use it:

begin
  qrySamples.LoadFromJSON('{"NAME":"Vinicius Sanchez","COUNTRY":"Brazil"}');
end;

Parameters

  • AOwns - Indicates who is responsible for destroying the passed JSON as a parameter;

LoadFromJSON

  • If JSON or DataSet has not been assigned, nothing will be done;
  • If DataSet is not activated and is not a TFDMemTable class, nothing will be done;
  • If the DataSet is of type TFDMemTable, it's not active and fields count equals zero, the fields will be created according to the JSON need. The DataType will be equal to ftString and Size equal to 4096;
  • When the "object_state" property is in JSON, the following validations are made:
    • If equal to INSERTED, an Append is performed on the DataSet;
    • If it is MODIFIED or DELETED, a Locate is made in the DataSet to find the record to be manipulated. If the registry is not found, nothing will be done. To execute Locate, a search for Key Fields is done within JSON;
    • If MODIFIED equals the Edit method of the DataSet;
    • If DELETED equals the Delete method of the DataSet;
  • If the "object_state" property is not found in JSON, then the Append method is called;
  • When loading a DataSet with JSON, fields that are ReadOnly are ignored;
  • If an attribute is not found in JSON with the field name (not case sensitive), or it is nullo, the field is ignored (nullo / empty);
  • When loading a DataSet with a JSON containing nested JSON using Master Detail, by convention, the name of the child DataSet is expected to be the same as the JSON attribute name that represents the list of children to be loaded. The name of the child DataSet may still have the initials qry (query) or mt (memtable), as these will be ignored;

Merge from JSON

With DataSet Serialize you can still change the DataSet registration simply by using MergeFromJSONObject. The function is similar to LoadFromJSON. An example of use is for REST servers when the verb used in the request is PUT (not necessarily), in this case we do not want to include a new record but to change the current record.

begin
  qrySamples.MergeFromJSONObject('{"NAME":"Vinicius","COUNTRY":"United States"}');
end;

Parameters

  • AOwns - Indicates who is responsible for destroying the passed JSON as a parameter;

MergeFromJSONObject

  • Same as LoadFromJSON validations;

Samples

Check out our sample project for each situation presented above in operation. If you have any questions or suggestion, please contact, make your pull request or create an issue.

dataset-serialize

Alone we go faster. Together we go further.

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

原工程地址:https://github.com/viniciussanchez/dataset-serialize 由于使用的了高版本的类信息所以无法在Delphi7中无法使用,这里将其他修改为使用superobject来做JSON部分的处理 展开 收起
Pascal
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Pascal
1
https://gitee.com/jsp007/dataset-serialize.git
git@gitee.com:jsp007/dataset-serialize.git
jsp007
dataset-serialize
dataset-serialize
master

搜索帮助