Bayesean Blog - Desktop, Mobile and IOT Developer Blog


Delphi Object directly to a Json string in a REST Client

Posted on 20th Aug 2018 in Delphi FMX


RestObjtjsonstr11.png

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.

restgif.gif

 

populateapp25.png

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:-

  • Create class name.
  • Set up object attributes of the class.
  • Set up a property per attribute which can read and write.

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

 

Code

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,

  Data.Bind.ObjectScope;

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.

sendingdata7.png

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

Download Code

Happy Coding

 

 


Be the First to Comment...

Add a Comment

9+5

Recent News

Delphi VCL Buttons in DBGrid
Two Helper Apps for Delphi LibUSB
Delphi Libusb Library Introduction
Delphi Object directly to a Json string in a REST Client
Delphi using Environment Variables in your App
Delphi FMX Leaflet Plotter using OSM Maps
C2PAS32 Convertor Application
C to Delphi Open Source Convertors Shootout

Categories

Bootstrap 4
Delphi VCL
Delphi FMX
Ajax
Bootstrap 3
CSS
XE4>Delphi > XE4
Delphi < XE4

Archives

October 2018

Delphi VCL Buttons in DBGrid
Two Helper Apps for Delphi LibUSB

September 2018

Delphi Libusb Library Introduction

August 2018

Delphi Object directly to a Json string in a REST Client
Delphi using Environment Variables in your App

July 2018

Delphi FMX Leaflet Plotter using OSM Maps

June 2018

C2PAS32 Convertor Application
C to Delphi Open Source Convertors Shootout
Delphi command-line programs with DOSCommand

May 2018

Delphi PDF Embedded viewer with PDF.js

March 2018

Delphi FMX - Changing TCharacter to TCharHelper
Make Your Delphi App POP using Javascript!

January 2018

Delphi FMX Dashboard using Chart.JS
Delphi FMX Form Docking

December 2017

PHP Slim REST Server & Delphi Auth Part 5

November 2017

Delphi FMX REST Client App Part 4

October 2017

Delphi VCL REST Pricing Client App Part 3

September 2017

Delphi REST VCL Client Basic Auth Part 2B

August 2017

Delphi REST Client Part 2A
PHP PDO REST Server Part 1

July 2017

PHP REST Server and Delphi Client Intro

June 2017

Delphi SQLite Encryptor-Decryptor Tool
Updating Applications Manifest using Delphi

May 2017

Create a Visual IP Address Geolocation with PHP

March 2017

PHP Downloader using Countdown timer
PHP File Downloader from a Inbox Selection

February 2017

Javascript Image-File Uploader with ThumbViewer

January 2017

Morris Charts and PHP-PDO

December 2016

CSS to create a functional Toggle Button