Posted on 20th Aug 2018 in Delphi FMX
Delphi Object directly to a Json string in a REST Client Example
This blog is the result of an Android REST Client project which was used to parse sensitive multiple email fields’ information to Json. Thereafter encrypted and sent as base64 code to a HTTPS REST Server using SSL. The REST Service uses an API key verification process.
I required a lightweight method for parsing Json. In my previous REST blogs all data was laboriously parsed using multiple Json libraries, so I stumbled upon another way that could lighten up the size of my Android APP with processed code. REST has REST.JSON which is nice and lightweight and offers a function “ObjecttoJsonString” conversion method. This library uses the not so light System.Json library and the REST.JsonReflect library.
Check out the gif below which demonstrates the sending of an email to a client via the REST Server. After receiving the REST post call. Note that this is demonstrated using the Xampp and a Php REST server operating in a localhost environment.
To get the multiple edit-box information into an object requires setting up a new class and adding published properties to it.
This seemed like more work but it in reality is not. If you are not familiar with class processes then I will give a few pointers on the subject. Furthermore using an object adds a layer of security to the Application in itself. So let’s run through what this entails…
Basic requirements for setting up an object:-
Now when you call the class name in the application an instance of the class name must be created in a variable as shown in the test example below.
TTest = class //create class ftestattribute : string; //Add more attributes ………………… published property testattribute read ftestattribute write ftestattribute; //Add more properties that read and write matching attributes ………………… end; Usage of the above code:- Procedure ………………………….; begin var test:Ttest;// create variable of class to gain access to the class …………………………. begin test.testattribute:= ‘add testattribute text to object test’; // populate the attribute of text
The key to this example is the function “ objecttoJsonString” used to convert the object directly into a Json string.
class function ObjectToJsonString(AObject: TObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): string;
As can be seen below, it uses the REST.json library is placed in the users list.
Uses ….. Rest.JSON, Rest.Client, Rest.Types, IPPeerClient, Data.Bind.Components,
The first step is to create the Object :-
A Class Temail is created with all the string items such as ffrom, fto etc.
Then we simply call “ jsonstr := TJson.ObjecttoJsonString(email);” to convert the object.
This could not get any easier so let’s take a look at the code between these actions:-
Whilst setting up the Class Temail. We also define the attributes of the object with published property read/write classes.
Type // create an object Temail which will be converted to a Json String Temail = class ffrom: string; ffrom_address: string; fcc: string; fto: string; fto_address: string; fsubject: string; fbody: string; published property from: string read ffrom write ffrom; property from_address: string read ffrom_address write ffrom_address; property cc: string read fcc write fcc; property &to: string read fto write fto; property to_address: string read fto_address write fto_address; property subject: string read fsubject write fsubject; property body: string read fbody write fbody; end; …….. Tfmmain = class(TForm) ……. The REST elements must be added to the global variable area so they are accessed from within the App. var fmmain: Tfmmain; Restrequest: TRestrequest; //add RestClient: TRestClient; //add RestResponse: TRestResponse; //add
The Button1click procedure will process the email and send the result directly to the REST Server. For testing, a memo loads all the actions that have or are taking place within the code. All this would be stripped out for production level code.
procedure Tfmmain.Button1Click(Sender: TObject); var email: Temail; // class to create jsonobject- eliminates a parser ContentType: TRestContenttype; SendContent: String; ResponseContent: String; jsonstr: string; begin Memo2.Lines.Clear; URL := 'https://Myrestserver’; // parse string to json object Memo2.Lines.Add('Creating Json Object.......'); Memo2.Lines.Add(''); email := Temail.Create; This adds each editbox’s text into the correct Object’s attribute. try email.to_address := Edit1.Text; email.&to := Edit2.Text; email.cc := Edit3.Text; email.from := Edit4.Text; email.from_address := Edit5.Text; email.subject := Edit6.Text; email.body := Memo1.Text; This is the step to convert the object to a Json string. // Add email object to json string jsonstr := TJson.ObjecttoJsonString(email); Memo2.Lines.Add('Encrypting json object string.....'); Memo2.Lines.Add(''); Memo2.Lines.Add(jsonstr); finally freeandnil(email); end; SendContent := trim(SendEncryptedContent); begin try //create the rest components RESTClient := TRESTClient.Create(URL); RESTrequest := TRESTrequest.Create(self); RESTResponse := TRESTResponse.Create(self); RESTrequest.Response := RESTResponse; RESTrequest.Client := RESTClient; RESTClient.ContentType := 'text/html'; RESTClient.Authenticator.Free; Contenttype:= ctMULTIPART_ENCRYPTED;//change if not encrypting // Add your APIKey here that your REST-Server will be expecting RESTrequest.Params.AddItem('Authorization', APIKey, TRESTRequestParameterKind.pkHTTPHEADER); RESTrequest.body.ClearBody; RESTrequest.body.Add(SendContent, ContentType); RESTrequest.method := TRESTRequestMethod.rmPost; try // post the encoded message RESTrequest.Execute; // 200 success! if RESTResponse.StatusCode <> 200 then begin ResponseContent := RESTResponse.Errormessage; end else begin // Add Successful message ResponseContent := RESTResponse.Content; memo2.lines.add(''); memo2.lines.add('REST-Server response.....'); Memo2.Lines.Add(ResponseContent); end except on exception: ERESTException do ResponseContent := 'Could not connect to Webserver'; on exception: ERequestError do ResponseContent := 'Could not connect to the Internet'; end; finally freeandnil(RESTClient); freeandnil(RESTrequest); freeandnil(RESTResponse); end; Memo2.GoToTextEnd; sleep(500); memo2.GoToTextBegin; end; end;
Most of the code was allocated to dynamically create the REST Client objects and freeing them after use.
That’s all to it. This code is pretty simple and easy to implement into any app.
Feel free to download the full win32 version code. Please note that the encryption information has been removed as this falls part of my self-developed proprietary IP.
Download from here
October 2018Delphi VCL Buttons in DBGrid
September 2018Delphi Libusb Library Introduction
August 2018Delphi Object directly to a Json string in a REST Client
July 2018Delphi FMX Leaflet Plotter using OSM Maps
June 2018C2PAS32 Convertor Application
May 2018Delphi PDF Embedded viewer with PDF.js
March 2018Delphi FMX - Changing TCharacter to TCharHelper
January 2018Delphi FMX Dashboard using Chart.JS
December 2017PHP Slim REST Server & Delphi Auth Part 5
November 2017Delphi FMX REST Client App Part 4
October 2017Delphi VCL REST Pricing Client App Part 3
September 2017Delphi REST VCL Client Basic Auth Part 2B
August 2017Delphi REST Client Part 2A
July 2017PHP REST Server and Delphi Client Intro
June 2017Delphi SQLite Encryptor-Decryptor Tool
May 2017Create a Visual IP Address Geolocation with PHP
March 2017PHP Downloader using Countdown timer
January 2017Morris Charts and PHP-PDO
December 2016CSS to create a functional Toggle Button