Categories
Delphi

TDocVariant CRUD Operations

This is based on http://blog.synopse.info/post/2014/02/25/TDocVariant-custom-variant-type and the corresponding forum http://synopse.info/forum/viewtopic.php?id=1631

Create

A TDocVariant custom variant type is declared as a Variant:

var
 LDocVariant : Variant;

The TDocVariant can be created as an object or from a JSON string. You can use the _Obj/_ObjFast, _JSON/_JSONFast and _Arr/_ArrFast methods to create the TDocVariant.

LDocVariant := _ObjFast( [ 'name', 'bernd' ] );
LDocVariant := _JsonFast( '{ "Person": { "First" : { "name" : "bernd" } } }' );
LDocVariant := _ArrFast( [ _ObjFast( [ 'name', 'bernd' ] ),
                           _ObjFast( [ 'name', 'bob' ] ) ] );

Read

You can access items in the TDocVariant variable dynamically:

Writeln( LDocVariant.name );
Writeln( LDocVariant.Person.First.Name )
Writeln( LDocVariant._(0).name );

Each of these will output “bernd”.

A TDocVariant will also be cast as JSON string when used in place of a string, for example, using the examples above, calling the following on each respectively:

Writeln( LDocVariant );

will output the following:

{"name":"bernd"}
{"Person":{"First":"bernd"}}
[{"name":"bernd"},{"name":"bob"}]

For arrays you also have _Count so you can iterate through the array:

for LIndex := 0 to LDocVariant._Count - 1 do
  Writeln( LDocVariant._(LIndex).name );

Update

Updating items and properties is really easy:

LDocVariant.name := "Bernd";
LDocVariant.Person.First.name := "Bernd";
LDocVariant._(1).name := "Bob";

You can add objects, array items or values to existing items as well.

LDocVariant.age := 31;
LDocVariant.Person.Next := _ObjFast( ['name','bob'] );
LDocVariant.Person.Next.age = 43;
LDocVariant.Add( _ObjFast( [ 'name', 'ned' ] ) );

Delete

All TDocVariant variables have the Delete method to remove an item from the object or array:

LDocVariant.Delete( 'name' );
LDocVariant.Person.Delete( 'Next' );
LDocVariant.Delete( 1 );

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.